为什么我在 Java 8 Lambda 中使用 "Collectors.toList()" 而不是 "Collectors::toList"?
Why I use "Collectors.toList()" rather than "Collectors::toList" in Java 8 Lambda?
通常在 flatMap
之后,我们使用 collect(Collectors.toList())
来收集数据,然后 return 使用 List
。
但为什么我不能使用 Collectors::toList
呢?我尝试使用它,但出现编译错误。
我试图搜索这个,但找不到任何解释。
非常感谢。
您正在调用 Stream
接口的 <R, A> R collect(Collector<? super T, A, R> collector)
方法。 Collectors.toList()
returns 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;
请参阅@Eran 的回答,因为它比我的更详细,但如果有人想要简单 解释:
您无法更改:
collect(Collectors.toList())
到 collect(Collectors::toList)
您只能更改:
collect(() -> Collectors.toList())
到 collect(Collectors::toList)
通常在 flatMap
之后,我们使用 collect(Collectors.toList())
来收集数据,然后 return 使用 List
。
但为什么我不能使用 Collectors::toList
呢?我尝试使用它,但出现编译错误。
我试图搜索这个,但找不到任何解释。
非常感谢。
您正在调用 Stream
接口的 <R, A> R collect(Collector<? super T, A, R> collector)
方法。 Collectors.toList()
returns 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;
请参阅@Eran 的回答,因为它比我的更详细,但如果有人想要简单 解释:
您无法更改:
collect(Collectors.toList())
到 collect(Collectors::toList)
您只能更改:
collect(() -> Collectors.toList())
到 collect(Collectors::toList)