How to understand this Java 8 Stream collect() method?

user3207158 :

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,

  1. Why is Collectors.toList() in this case returns an ArrayList<Integer> implementing List interface? Why not LinkedList<Integer> or any other generic class conforming to List interface? I can't find anything about this, except for a brief mentioning of ArrayList here, in the API Notes section.

  2. What does the left panel of enter image description here Stream.collect() mean? Obviously R 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.

Andronicus :
  1. 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 for Collection you wish:

    Arrays.stream(arr).boxed().collect(toCollection(LinkedList::new));
    
  2. Yes, A and R are generic parameters of this method, R is the return type, T is the input type and A 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 of Collector'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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=321737&siteId=1