本文介绍了Java Stream Collectors.toList()不会编译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
任何人都可以解释为什么下面的代码不能编译但第二个代码会编译吗?
Can any one explain why the below code will not compile but the second one does?
不编译
private void doNotCompile() {
List<Integer> out;
out = IntStream
.range(1, 10)
.filter(e -> e % 2 == 0)
.map(e -> Integer.valueOf(2 * e))
.collect(Collectors.toList());
System.out.println(out);
}
收集行的编译错误
- IntStream类型中的方法collect(Supplier,ObjIntConsumer,BiConsumer)不适用于参数(Collector>)
- 类型不匹配:无法从收集器>转换为供应商
编译
private void compiles() {
List<Integer> in;
in = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
List<Integer> out;
out = in.stream()
.filter(e -> e % 2 == 0)
.map(e -> 2 * e)
.collect(Collectors.toList());
System.out.println(out);
}
推荐答案
IntStream
没有接受收集器
的 collect
方法。如果你想要 List< Integer>
,你必须将 IntStream
打包成 Stream< ;整数>
:
IntStream
doesn't have a collect
method that accepts a Collector
. If you want a List<Integer>
, you have to box the IntStream
into a Stream<Integer>
:
out = IntStream
.range(1, 10)
.filter(e -> e % 2 == 0)
.map(e -> 2 * e)
.boxed()
.collect(Collectors.toList());
替代 .map()。boxed()
是 mapToObj()
:
out = IntStream
.range(1, 10)
.filter(e -> e % 2 == 0)
.mapToObj(e -> 2 * e)
.collect(Collectors.toList ());
或者您可以使用 IntStream
收集
方法:
or you can use the IntStream
collect
method:
out = IntStream
.range(1, 10)
.filter(e -> e % 2 == 0)
.map(e -> 2 * e)
.collect(ArrayList<Integer>::new, ArrayList::add, ArrayList::addAll);
这篇关于Java Stream Collectors.toList()不会编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!