3

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

但是为什么我不能使用Collectors::toList呢?我尝试使用它,但出现编译错误。

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

非常感谢。

4

2 回答 2

7

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

你不能改变:

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

你只能改变:

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

于 2018-07-02T09:32:56.157 回答
6

您正在调用接口的<R, A> R collect(Collector<? super T, A, R> collector)方法StreamCollectors.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;
于 2018-07-02T09:30:11.400 回答