New convenience methods on Stream
donraab at gmail.com
Tue Apr 27 05:08:28 UTC 2021
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)
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());
Set<String> set = stream.to(Set::of);
List<String> list = stream.to(List::of);
List<String> arrayList = stream.to(Arrays::asList);
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());
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