1 回答

TA貢獻(xiàn)1872條經(jīng)驗(yàn) 獲得超4個(gè)贊
您看不到StringBuilder
,因?yàn)槭褂?a 的結(jié)果StringBuilder
是 a?String
。這StringBuilder
是在幕后使用的。
例子
String[] input = { "Hell", "oW", "orld" };
String joined = Stream.of(input).collect(Collectors.joining());
System.out.println(joined); // prints: HelloWorld
如果你在沒有流媒體的情況下執(zhí)行此操作,你會(huì)這樣做:
StringBuilder buf = new StringBuilder();
for (String s : input)
? ? buf.append(s);
String joined = buf.toString();
這也是流正在做的事情。如果你查看源碼joining(),你會(huì)發(fā)現(xiàn):
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()
。
另外兩個(gè)重載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
如果你在沒有流媒體的情況下執(zhí)行此操作,你會(huì)這樣做:
StringBuilder buf = new StringBuilder();
for (String s : input)
? ? buf.append(s);
String joined = buf.toString();
這也是流正在做的事情。如果你查看源碼joining(),你會(huì)發(fā)現(xiàn):
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);
}
添加回答
舉報(bào)