我只是想创建有点类似于我自己的 Collectors.toList()
但它似乎不起作用
import java.util.ArrayList;
public class ShipmentTracingDTO {
boolean destination = false;
public ShipmentTracingDTO(Boolean destination) {
this.destination = destination;
}
public ShipmentTracingDTO() {
}
public static void main(String[] args) {
ArrayList<ShipmentTracingDTO> tracings = new ArrayList<>();
tracings.add(new ShipmentTracingDTO(true));
tracings.add(new ShipmentTracingDTO(true));
tracings.add(new ShipmentTracingDTO(false));
tracings.add(new ShipmentTracingDTO(false));
ArrayList<ShipmentTracingDTO> newTracings = new ArrayList<>();
// Error coming for ArrayList::new : The constructed object of type ArrayList is
//incompatible with the descriptor's return type: R
tracings.stream().collect(ArrayList::new, (left, right) -> left.add(right), (left, right) -> {
left.addAll(right);
return left;
});
}
private boolean getDestination() {
return destination;
}
我的问题是,如果 ArrayList::new
在这里不起作用,那么什么会起作用。我尝试了不同的变体,但似乎都不起作用
最佳答案
就这样改吧
tracings.stream().collect(ArrayList::new, (left, right) -> left.add(right), (left, right) -> {
left.addAll(right);
});
您需要的是 BiConsumer
而不是 BinaryOperator
。您在上面传递的是 BinaryOperator
。
这是一个示例 BinaryOperator
。
BinaryOperator<List<Integer>> s = (left, right) -> {
left.addAll(right);
return left;
};
作为一种良好的工程实践,始终优先使用方法引用而不是 lambda。所以这是使用方法引用代替 lambda 的增强版本。
tracings.stream().collect(ArrayList::new, List::add, List::addAll);
关于java - 流收集方法的有效供应商,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54124208/