Stream.collect方法中的组合器如何在java 8中工作? [英] How does combiner in Stream.collect method work in java 8?
问题描述
我创建了简单的演示:
public static void main(String[] args) {
List<String> list2 = Arrays.asList("adf", "bcd", "abc", "hgr", "jyt", "edr", "biu");
String collect = list2.stream().collect(String::new, (res, elem) -> {
res=res.concat(" ").concat(elem);
// System.out.printf("res=%s, elem=%s\n", res.isEmpty(), elem);
}, (res1, res2) -> {
System.out.printf("res1=%s, res2=%s\n", res1, res2);
});
System.out.println("collect=" + collect);
}
问题在于 BiConsumer组合器
collect
的一部分根本不运行。
The problem is that BiConsumer combiner
part of collect
doesn't run at all.
如果我使用<$ c $它会运行c> parallelStream()但是两个参数 res1
和 res2
等于supplier String :: new
。
It runs if I use parallelStream()
but two arguments res1
and res2
are equal to supplier String::new
.
如何使组合器
工作收集
方法?
推荐答案
首先,没有必要组合器在非并行流中执行,因为没有什么可以组合。
First off, there is no need for the combiner to be executed in a non-parallel stream since there is nothing to combine.
其次,你的问题源于使用 String :: new
和 String.concat
。累加器应该通过将第二个参数与它组合来修改第一个参数,但由于Java中的字符串是不可变的,因此代码将不会产生任何内容。
Secondly, your issue stems from using String::new
and String.concat
. The accumulator is supposed to modify the first argument by combining the second argument with it but since strings in Java are immutable your code will produce nothing.
res=res.concat(" ").concat(elem);
将创建一个新字符串然后扔掉它。您希望使用StringBuilder,以便保留中间结果:
will create a new string and then throw away it. You want to use a StringBuilder instead so you can keep the intermediate results:
public static void main(String[] args) {
List<String> list2 = Arrays.asList("adf", "bcd", "abc", "hgr", "jyt", "edr", "biu");
String collect = list2.stream().collect(StringBuilder::new, (res, elem) -> {
res.append(" ").append(elem);
}, (res1, res2) -> {
res1.append(res2.toString());
System.out.printf("res1=%s, res2=%s\n", res1, res2);
}).toString();
System.out.println("collect=" + collect);
}
这对于并行流也能正常工作
This will also work correctly with a parallel stream
res1 = hgr jyt,res2 = jyt
res1 = bcd abc,res2 = abc
res1 = adf bcd abc ,res2 = bcd abc
res1 = edr biu,res2 = biu
res1 = hgr jyt edr biu,res2 = edr biu
res1 = adf bcd abc hgr jyt edr biu,res2 = hgr jyt edr biu
collect = adf bcd abc hgr jyt edr biu
res1= hgr jyt, res2= jyt
res1= bcd abc, res2= abc
res1= adf bcd abc, res2= bcd abc
res1= edr biu, res2= biu
res1= hgr jyt edr biu, res2= edr biu
res1= adf bcd abc hgr jyt edr biu, res2= hgr jyt edr biu
collect= adf bcd abc hgr jyt edr biu
这篇关于Stream.collect方法中的组合器如何在java 8中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!