考虑以下未编译的示例:
代码将被编译。 那么问题是,我该如何使用供应商和累加器(我需要它)编写
例如:
List<Integer> list = Arrays.asList(1, 2, -3, 8);
list.stream()
.filter(x -> x > 0)
.collect(ArrayList::new, ArrayList::add, ArrayList::addAll)
.stream() // Stream<Object>
.map(x -> x * 2)
.forEach(System.out::println);
如果我替换
.collect(ArrayList::new, ArrayList::add, ArrayList::addAll)
使用
.collect(Collectors.toList())
代码将被编译。 那么问题是,我该如何使用供应商和累加器(我需要它)编写
collect()
,以便在之后调用stream()
?
ArrayList
。请使用ArrayList<Integer>::new
。 - ernest_kArrayList<Integer>::new
并不总是必需的,例如,List<Integer> anotherList = list.stream().collect(ArrayList::new, ArrayList::add, ArrayList::addAll)
也可以正常工作。 - MC Emperor