为什么在Java8Lambda中使用“Collectors.toList()”而不是“Collectors::toList”?
通常在flatMap
之后,我们使用collect(Collectors.toList())
收集数据并返回List
但是为什么我不能用Collectors::toList
来代替呢?我试图使用它,但出现了编译错误
我试图搜索这个,但找不到任何解释
非常感谢
你可以在下面搜索框中键入要查询的问题!
通常在flatMap
之后,我们使用collect(Collectors.toList())
收集数据并返回List
但是为什么我不能用Collectors::toList
来代替呢?我试图使用它,但出现了编译错误
我试图搜索这个,但找不到任何解释
非常感谢
# 1 楼答案
您正在调用
Stream
接口的<R, A> R collect(Collector<? super T, A, R> collector)
方法Collectors.toList()
返回一个Collector<T, ?, List<T>>
,它与collect
方法参数的必需类型匹配。因此someStream.collect(Collectors.toList())
是正确的另一方面,方法引用
Collectors::toList
不能作为collect
方法的参数,因为方法引用只能在需要函数接口的地方传递,而Collector
不是函数接口您可以将
Collectors::toList
传递给需要Supplier<Collector>
的方法。类似地,您可以将其分配给这样一个变量:# 2 楼答案
请看@Eran答案,因为它比我的答案更详细,但如果有人想要一个简单的解释:
你不能改变:
collect(Collectors.toList())
到collect(Collectors::toList)
你只能改变:
collect(() -> Collectors.toList())
到collect(Collectors::toList)