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 results =…).collect(Collectors.toList());
  • Get an implementation Set arbitrary containing the result:

    Set results =…).collect(Collectors.toSet());
  • Get a specific Collection:

    ArrayList results =…).collect(Collectors.toCollection(ArrayList::new));
  • Add to a Collection existing:…).forEach(existing::add);
  • Create an array:

  • Use the array to create a list with specific specific behavior (editable, fixed size):

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

    List results
      =…).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