New convenience methods on Stream

Donald Raab donraab at
Tue Apr 27 05:08:28 UTC 2021

Hi all,

I’d like to propose adding one or two of the following methods on Stream to cover more surface area of the Collections ecosystem, without requiring a big increase in the size of the Stream interface. Apologies if this has come up for discussion before. 

1. Stream contents into a mutable collection created by a Supplier. 

default <R extends Collection<T>> R toCollection(Supplier<R> supplier)
    return this.collect(Collectors.toCollection(supplier));

Usage Examples:

HashSet<String> set = stream.toCollection(HashSet::new);
TreeSet<String> sortedSet = stream.toCollection(TreeSet::new);
ArrayDeque<String> deque = stream.toCollection(ArrayDeque::new);

2. Pass the result of toArray directly into a function that can then return a Collection. This should work with Set.of, List.of and any 3rd party collections which take arrays.

default <R extends Collection<T>> R to(Function<T[], R> function)
    return function.apply((T[]) this.toArray());

Usage Examples:

Set<String> set =;
List<String> list =;
List<String> arrayList =;

3. Stream contents directly into any mutable collection. This would then work with all other mutable JDK Collection types.

default <R extends Collection<T>> R into(R result)
    Collections.addAll(result, (T[]) this.toArray());
    return result;

Usage Examples:

HashSet<String> set = stream.into(new HashSet<>());
TreeSet<String> sortedSet = stream.into(new TreeSet<>(Comparator.reverseOrder()));
CopyOnWriteArrayList<String> list = stream.into(new CopyOnWriteArrayList<>());

There may be better default implementations, but I just wanted something here for illustrative purposes.



More information about the core-libs-dev mailing list