java – Collection for streaming to a new collection

There is a reason why most examples avoid storing the result in a Collection. This is not the recommended way of programming. You already have a Collection, the one that provides the source data and the collections is not in itself useful. You want to perform certain operations on it, so the ideal case is to perform the operation using the stream and skip storing the data in a Collection intermediate. This is what most of the examples try to suggest.

Of course, there are a lot of existing APIs that they work with Collectionif they will always be there. Hence the API Stream offers several ways to manage the demand for Collection.

  • Get an implementation List arbitrary containing the result:

    List<T> results = l.stream().filter(…).collect(Collectors.toList());
    
  • Get an implementation Set arbitrary containing the result:

    Set<T> results = l.stream().filter(…).collect(Collectors.toSet());
    
  • Get a specific Collection:

    ArrayList<T> results =
      l.stream().filter(…).collect(Collectors.toCollection(ArrayList::new));
    
  • Add to a Collection existing:

    l.stream().filter(…).forEach(existing::add);
    
  • Create an array:

    String[] array=l.stream().filter(…).toArray(String[]::new);
    
  • Use the array to create a list with specific specific behavior (editable, fixed size):

    List<String> al=Arrays.asList(l.stream().filter(…).toArray(String[]::new));
    
  • Allow a parallel-capable stream to add itself to temporary local lists and merge them later:

    List<T> results
      = l.stream().filter(…).collect(ArrayList::new, List::add, List::addAll);
    

    (Note: this is closely related to the way Collectors.toList() is currently implemented, but this is an implementation detail, ie there is no guarantee that future collector implementations toList() they will still return a ArrayList)

Leave a comment