守着一只汪
您看不到StringBuilder,因为使用 a 的结果StringBuilder是 a String。这StringBuilder是在幕后使用的。例子String[] input = { "Hell", "oW", "orld" };String joined = Stream.of(input).collect(Collectors.joining());System.out.println(joined); // prints: HelloWorld如果你在没有流媒体的情况下执行此操作,你会这样做:StringBuilder buf = new StringBuilder();for (String s : input) buf.append(s);String joined = buf.toString();这也是流正在做的事情。如果你查看源码joining(),你会发现:public static Collector<CharSequence, ?, String> joining() { return new CollectorImpl<CharSequence, StringBuilder, String>( StringBuilder::new, StringBuilder::append, (r1, r2) -> { r1.append(r2); return r1; }, StringBuilder::toString, CH_NOID);}正如您所看到的,它还使用new StringBuilder()、append(CharSequence s)和toString()。另外两个重载joining(CharSequence delimiter)和joining(CharSequence delimiter, CharSequence prefix, CharSequence suffix),使用StringJoiner而不是StringBuilder。String[] input = { "Hell", "oW", "orld" };String joined = Stream.of(input).collect(Collectors.joining());System.out.println(joined); // prints: HelloWorld如果你在没有流媒体的情况下执行此操作,你会这样做:StringBuilder buf = new StringBuilder();for (String s : input) buf.append(s);String joined = buf.toString();这也是流正在做的事情。如果你查看源码joining(),你会发现:public static Collector<CharSequence, ?, String> joining() { return new CollectorImpl<CharSequence, StringBuilder, String>( StringBuilder::new, StringBuilder::append, (r1, r2) -> { r1.append(r2); return r1; }, StringBuilder::toString, CH_NOID);}