Collecting to a Collection

The method toCollection(Supplier) creates a collector that uses a mutable container of a specific Collection type to perform mutable reduction. A supplier to create the mutable container is specified as an argument to the method.

The following stream pipeline creates an ArrayList<String> instance with the titles of all CDs in the stream. The constructor reference ArrayList::new returns an empty ArrayList<String> instance, where the element type String is inferred from the context.

Click here to view code image

ArrayList<String> cdTitles1 = CD.cdList.stream() // Stream<CD>
    .map(CD::title)                              // Stream<String>
    .collect(Collectors.toCollection(ArrayList::new));
//[Java Jive, Java Jam, Lambda Dancing, Keep on Erasing, Hot Generics]

Click here to view code image

static <T,C extends Collection<T>> Collector<T,?,C>
       toCollection(Supplier<C> collectionFactory)

Returns a Collector that accumulates the input elements of type T into a new Collection of type C, in encounter order. A new empty Collection of type C is created by the collectionFactory supplier, thus the collection created can be of a specific Collection type.

Click here to view code image

static <T> Collector<T,?,List<T>> toList()
static <T> Collector<T,?,List<T>> toUnmodifiableList()

Return a Collector that accumulates the input elements of type T into a new List or an unmodifiable List of type T, respectively, in encounter order.

The toList() method gives no guarantees of any kind for the returned list.

The unmodifiable list returned does not allow null values.

See also the Stream.toList() terminal operation (p. 972).

Click here to view code image

static <T> Collector<T,?,Set<T>> toSet()
static <T> Collector<T,?,Set<T>> toUnmodifiableSet()

Return an unordered Collector that accumulates the input elements of type T into a new Set or an unmodifiable Set of type T, respectively.

Collecting to a List

The method toList() creates a collector that uses a mutable container of type List to perform mutable reduction. This collector guarantees to preserve the encounter order of the input stream, if it has one. For more control over the type of the list, the toCollection() method can be used. This collector can be used as a downstream collector.

The following stream pipeline creates a list with the titles of all CDs in the stream using a collector returned by the Collectors.toList() method. Although the returned list is modified, this is implementation dependent and should not be relied upon.

Click here to view code image

List<String> cdTitles3 = CD.cdList.stream()      // Stream<CD>
    .map(CD::title)                              // Stream<String>
    .collect(Collectors.toList());
//[Java Jive, Java Jam, Lambda Dancing, Keep on Erasing, Hot Generics]
titles.add(“Java Jingles”);                      // OK

Leave a Reply

Your email address will not be published. Required fields are marked *