为什么我在Java 8 Lambda中使用"Collectors.toList()"而不是"Collectors :: toList"?

Niu*_*ang 2 java lambda tolist collectors

通常在a之后flatMap,我们collect(Collectors.toList())用来收集数据并返回一个List.

但为什么我不能用Collectors::toList呢?我试图使用它,但得到了编译错误.

我试图搜索这个,但找不到任何解释.

非常感谢.

Dan*_*non 6

请参阅@Eran的答案,因为它比我的更详细,但如果有人想要一个简单的解释:

你无法改变:

collect(Collectors.toList())collect(Collectors::toList)

你只能改变:

collect(() -> Collectors.toList())collect(Collectors::toList)


Era*_*ran 5

您正在调用接口的<R, A> R collect(Collector<? super T, A, R> collector)方法Stream.Collectors.toList()返回a Collector<T, ?, List<T>>,它匹配collect方法参数的必需类型.因此someStream.collect(Collectors.toList())是正确的.

另一方面,方法引用Collectors::toList不能作为collect方法的参数,因为方法引用只能在需要功能接口的地方传递,而Collector不是功能接口.

您可能已经传递Collectors::toList给需要的方法Supplier<Collector>.同样,您可以将其分配给这样的变量:

Supplier<Collector<Object,?,List<Object>>> supplierOfListCollector = Collectors::toList;
Run Code Online (Sandbox Code Playgroud)