I was trying to convert an int array to List and I took the unfamiliar route of using Java 8 Stream and came up with this
Arrays.stream(arr).boxed().collect(Collectors.toList());
I still have difficulty fully understand this line, mostly,
Why is
Collectors.toList()
in this case returns anArrayList<Integer>
implementingList
interface? Why notLinkedList<Integer>
or any other generic class conforming toList
interface? I can't find anything about this, except for a brief mentioning of ArrayList here, in the API Notes section.What does the left panel of
Stream.collect()
mean? ObviouslyR
is the generic return type (ArrayList<Integer>
in my code here). And I think<R, A>
is the generic type argument of the method, but how are they specified? I looked into Collector interface doc and was not able to absorb it.
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