下面的代码:
public class Test {
public static void main(String[] args) {
Stream.of(1, 2, 3).map(String::valueOf).collect(Collectors::toList);
}
}
IntelliJ 告诉我:
Collector<String, A, R>
不是函数式接口(interface)
但是当我修改如下代码时,一切正常,不知道为什么?
public class Test {
public static void main(String[] args) {
Stream.of(1, 2, 3).map(String::valueOf).collect(Collectors.<String>toList());
}
}
最佳答案
第一种语法不合法的原因是方法签名隐含的目标类型— Stream.collect(Collector)
—是Collector
. Collector
有多个抽象方法,所以它不是函数式接口(interface),不能有 @FunctionalInterface
注释。
方法引用,如 Class::function
或 object::method
只能分配给功能接口(interface)类型。自 Collector
不是功能接口(interface),不能使用方法引用来为 collect(Collector)
提供参数.
相反,调用 Collectors.toList()
作为一个功能。明确的 <String>
type 参数是不必要的,如果最后没有括号,你的“工作”示例将无法工作。这将创建一个 Collector
可以传递给 collect()
的实例.
关于java 8 Collector<String, A, R> 不是函数式接口(interface),谁能告诉我为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32094174/