我试图将int数组转换为List,然后我走了一条不熟悉的使用Java 8 Stream的路线,并提出了这个
Arrays.stream(arr).boxed().collect(Collectors.toList());
大多数情况下,我还是很难完全理解这一行
我试图将int数组转换为List,然后我走了一条不熟悉的使用Java 8 Stream的路线,并提出了这个
Arrays.stream(arr).boxed().collect(Collectors.toList());
大多数情况下,我还是很难完全理解这一行
这是默认实现。使用ArrayList
是因为它在大多数情况下都是最好的,但是如果它不适合您,则可以随时定义自己的收集器并为您希望的Collection
提供工厂:
Arrays.stream(arr).boxed().collect(toCollection(LinkedList::new));
是,A
和R
是此方法的通用参数,R
是返回类型,T
是输入类型,{{1} }是一种中间类型,它出现在收集元素的整个过程中(可能不可见,并且与该功能无关)。您提供的javadoc的开头定义了这些类型(它们在整个文档中都是一致的):
,T-归约运算的输入元素的类型
A-归约运算的可变累积类型(通常隐藏为实现细节)
R-归约运算的结果类型
如方法定义所建议的,它返回收集器提供者为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);
}
<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);