如何理解此Java 8 Stream collect()方法?

我试图将int数组转换为List,然后我走了一条不熟悉的使用Java 8 Stream的路线,并提出了这个

Arrays.stream(arr).boxed().collect(Collectors.toList());

大多数情况下,我还是很难完全理解这一行

  1. 在这种情况下,为什么Collectors.toList()返回实现ArrayList<Integer>的{​​{1}}接口?为什么不使用List或符合LinkedList<Integer>接口的任何其他通用类?除了在API注释部分中对ArrayList here的简短提及之外,我对此一无所获。

  2. 什么是左面板

    如何理解此Java 8 Stream collect()方法?

    List是什么意思?显然Stream.collect()是通用返回类型(这里的代码中是R)。而且我认为ArrayList<Integer>是方法的泛型类型参数,但是如何指定它们呢?我查看了Collector界面文档,但无法吸收它。

eventuallyfantasy 回答:如何理解此Java 8 Stream collect()方法?

  1. 这是默认实现。使用ArrayList是因为它在大多数情况下都是最好的,但是如果它不适合您,则可以随时定义自己的收集器并为您希望的Collection提供工厂:

    Arrays.stream(arr).boxed().collect(toCollection(LinkedList::new));
    
  2. 是,AR是此方法的通用参数,R是返回类型,T是输入类型,{{1} }是一种中间类型,它出现在收集元素的整个过程中(可能不可见,并且与该功能无关)。您提供的javadoc的开头定义了这些类型(它们在整个文档中都是一致的):

  

T-归约运算的输入元素的类型

     

A-归约运算的可变累积类型(通常隐藏为实现细节)

     

R-归约运算的结果类型

,
  1. 在这种情况下,为什么Collectors.toList()返回实现List接口的ArrayList?

如方法定义所建议的,它返回收集器提供者为ArrayList的收集器实现。因此,从下面的方法定义中很明显,Collectors.toList总是返回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);
    }
  1. <R,A> R collect(Collector<? super T,A,R> collector)的左面板是什么意思

如果您参考文档注释,它准确地提到了这些通用类型是什么:

/*
      @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,R> collector);
本文链接:https://www.f2er.com/3168728.html

大家都在问