通常在a之后flatMap
,我们collect(Collectors.toList())
用来收集数据并返回a List
。
但是为什么我不能使用Collectors::toList
呢?我尝试使用它,但出现编译错误。
我试图搜索这个,但找不到任何解释。
非常感谢。
通常在a之后flatMap
,我们collect(Collectors.toList())
用来收集数据并返回a List
。
但是为什么我不能使用Collectors::toList
呢?我尝试使用它,但出现编译错误。
我试图搜索这个,但找不到任何解释。
非常感谢。
请参阅@Eran 答案,因为它比我的更详细,但如果有人想要一个简单的解释:
你不能改变:
collect(Collectors.toList())
到collect(Collectors::toList)
你只能改变:
collect(() -> Collectors.toList())
到collect(Collectors::toList)
您正在调用接口的<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;