How to use collect call in Java 8?

后端 未结 2 1052
梦谈多话
梦谈多话 2021-02-12 09:11

Lets say we have this boring piece of code that we all had to use:

ArrayList ids = new ArrayList();
for (MyObj obj : myList){
    ids.add         


        
2条回答
  •  攒了一身酷
    2021-02-12 10:11

    The issue is that Collectors.toList, not surprisingly, returns a List. Not an ArrayList.

    List ids = remove.stream()
            .map(MyObj::getId)
            .collect(Collectors.toList());
    

    Program to the interface.

    From the documentation:

    Returns a Collector that accumulates the input elements into a new List. There are no guarantees on the type, mutability, serializability, or thread-safety of the List returned; if more control over the returned List is required, use toCollection(Supplier).

    Emphasis mine - you cannot even assume that the List returned is mutable, let alone that it is of a specific class. If you want an ArrayList:

    ArrayList ids = remove.stream()
            .map(MyObj::getId)
            .collect(Collectors.toCollection(ArrayList::new));
    

    Note also, that it is customary to use import static with the Java 8 Stream API so adding:

    import static java.util.stream.Collectors.toCollection;
    

    (I hate starred import static, it does nothing but pollute the namespace and add confusion. But selective import static, especially with the Java 8 utility classes, can greatly reduce redundant code)

    Would result in:

    ArrayList ids = remove.stream()
            .map(MyObj::getId)
            .collect(toCollection(ArrayList::new));
    

提交回复
热议问题