[英]How to understand this Java 8 Stream collect() method?
我试图将一个 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
是输入类型, A
是中间类型,在整个收集元素的过程中都会出现(可能不可见,不关心这个函数) )。 Collector
的 javadoc 的开头定义了这些类型(它们在整个 doc 中是一致的):
T - 归约操作的输入元素类型
A - 归约操作的可变累积类型(通常作为实现细节隐藏)
R - 归约操作的结果类型
正如方法定义所暗示的,它返回一个收集器实现,收集器供应商为ArrayList
。 因此,从下面的方法定义中非常清楚Collectors.toList
总是返回 ArrayList 收集器( 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, A> R collect(Collector<? super T, A, R> collector);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.