Java Stream Collectors.toList()不会编译
发布时间:2020-12-15 04:49:18 所属栏目:Java 来源:网络整理
导读:任何人都可以解释为什么下面的代码不能编译但第二个代码呢? 不要编译 private void doNotCompile() { ListInteger out; out = IntStream .range(1,10) .filter(e - e % 2 == 0) .map(e - Integer.valueOf(2 * e)) .collect(Collectors.toList()); System.ou
任何人都可以解释为什么下面的代码不能编译但第二个代码呢?
不要编译 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< 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收集方法: out = IntStream .range(1,10) .filter(e -> e % 2 == 0) .map(e -> 2 * e) .collect(ArrayList<Integer>::new,ArrayList::add,ArrayList::addAll); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |