流收集方法的有效供应商

Valid Supplier for collect method of stream

我只是想创建一些类似于我自己的 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 在这里不起作用,那么什么会起作用。我尝试了不同的变体,但 none 似乎有效

您似乎在寻找:

tracings.stream()
        .collect(ArrayList::new, 
                 ArrayList::add, 
                 ArrayList::addAll);

与 lambda 表示相同:

tracings.stream()
        .collect(ArrayList::new, 
                 (left, right) -> left.add(right), 
                 (left, right) -> left.addAll(right)); // notice no 'return'

原因Stream.collect 需要一个 BiConsumer 作为参数,它有一个 accept 方法和 voidreturn类型。

就这么改,

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);

I was just trying to create somewhat similar to Collectors.toList() of my own but it doesn't seem to work

虽然其他答案指定了您做错了什么,但值得注意的是,如果您尝试创建类似于 toList() 但同时指定返回列表的类型,那么我会建议使用专门为此目的制作的 toCollection

tracings.stream().collect(Collectors.toCollection(ArrayList::new));

虽然这并不比:

new ArrayList<>(tracings);

更短更易读。