【发布时间】:2017-10-19 10:34:25
【问题描述】:
谁能解释为什么下面的代码不能编译,而第二个却可以?
不要编译
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);
}
collect 行出现编译错误
- IntStream 类型中的方法 collect(Supplier, ObjIntConsumer, BiConsumer) 不适用于参数 (Collector>)
- 类型不匹配:无法从 Collector> 转换为 Supplier
编译
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);
}
【问题讨论】:
-
下一次,添加错误消息,而不是仅仅声明它不会编译。
标签: java java-stream collectors