How to understand this Java 8 Stream collect() method?
It's a default implementation.
ArrayList
is used, because it's best in most use cases, but if it's not suitable for you, you can always define your own collector and provide factory forCollection
you wish:Arrays.stream(arr).boxed().collect(toCollection(LinkedList::new));
Yes,
A
andR
are generic parameters of this method,R
is the return type,T
is the input type andA
is an intermediate type, that appears in the whole process of collecting elements (might not be visible and does not concern this function). The beginning ofCollector
's javadoc defines those types (they are consistent across the entire doc):T - the type of input elements to the reduction operation
A - the mutable accumulation type of the reduction operation (often hidden as an implementation detail)
R - the result type of the reduction operation
- Why is Collectors.toList() in this case returns an ArrayList implementing List interface?
As the method definition suggests it returns a Collector implementation with collector supplier as ArrayList
. Hence, it's very clear from method definition below that Collectors.toList
always returns ArrayList collector(While it's arguable why toList not toArrayList word is used in method name
).
public static <T>
Collector<T, ?, List<T>> toList() {
return new CollectorImpl<>((Supplier<List<T>>) ArrayList::new, List::add,
(left, right) -> { left.addAll(right); return left; },
CH_ID);
}
- What does the left panel of
<R, A> R collect(Collector<? super T, A, R> collector)
means
If you refer to documentation comments it accurately mentions what these generic types are:
/*
@param <R> the type of the result
@param <A> the intermediate accumulation type of the {@code Collector}
@param collector the {@code Collector} describing the reduction
@return the result of the reduction
*/
<R, A> R collect(Collector<? super T, A, R> collector);