在Stream的collect()终端操作中,如果supplier是一个像String这样的不可变

collect()Stream 的方法是可变的归约。基于 Java 文档:


可变归约操作在处理流中的元素时将输入元素累积到可变结果容器中,例如 Collection 或 StringBuilder。


我尝试了以下方法,它编译没有问题。


Stream<String> stream1 = Stream.of("w", "o", "l", "f");

String word = stream1.collect(String::new, String::concat, String::concat);

System.out.println(word);

如果供应商是 StringBuffer,我会查看收集操作,因为元素将附加到提供的 StringBuffer。


由于 String 是不可变对象,可变归约在这里如何工作?它是否与每次实现累加器时创建新对象的reduce操作相同?


小怪兽爱吃肉
浏览 258回答 2
2回答

烙印99

由于 String 是一个不可变对象,可变归约在这里如何工作?它没有。当您运行它时,您将获得一个空字符串( 的结果Supplier only)。编译器不能强制检查供应商是否返回不可变对象,这绝对是它不能做的事情。由于你的容器是不可变的,对它的更新会被简单地忽略。这就像做:String s = "abc";s.concat("def"); // the result is ignored here可能如果你把它写成一个 lambda,它会更有意义:Stream<String> stream1 = Stream.of("w", "o", "l", "f");&nbsp; &nbsp; String word = stream1.collect(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String::new,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; (left, right) -> {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; left.concat(right); // result is ignored&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String::concat);另一方面,当你使用 reduce 时,你会被迫返回一些东西:String word = stream1.reduce(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; (x, y) -> {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return x.concat(y);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; (x, y) -> {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return x.concat(y);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });当然,你仍然可以这样做:String word = stream1.reduce(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; (x, y) -> {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; x.concat(y);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return x; // kind of stupid, but you could&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; (x, y) -> {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return x.concat(y);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });如果你想打破它;但这不是重点。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java