【发布时间】:2021-06-25 09:01:13
【问题描述】:
我在输入 reduce 操作的累加器时遇到问题,原因有两个。
首先,我从这篇文章中了解到,在使用(identity, accumulator)签名时,如果返回类型与被归约集合内部的不同,则需要有一个显式的@987654322 @ 帮助编译器。然而,返回类型总是由我们传递的身份明确表示!为什么编译器不能自己推断出这也是一样的?
List<String> productNames =
products.stream()
.reduce(
new ArrayList<>(),
(acc, elm) -> {
List<String> newList = new ArrayList<>(acc);
newList.add(elm.getName());
return newList; // Won't compile!
});
第二,当我尝试创建当前累积值的副本时,我必须显式传递具体类型而不仅仅是接口,就像我们通常使用列表所做的那样。
List<String> productNames =
products.stream()
.reduce(
new ArrayList<>(),
(acc, elm) -> {
List<String> newList = new ArrayList<>(acc); // Won't compile! needs ArrayList<String>
newList.add(elm.getName());
return newList;
},
(list1, list2) -> {
ArrayList<String> newList = new ArrayList<>(list2);
newList.addAll(list1);
return newList;
});
【问题讨论】:
-
请添加编译错误。