本文介绍了java 8 Collector< String,A,R>不是功能界面,谁能说出原因?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码:

public class Test {
    public static void main(String[] args) {

        Stream.of(1,2,3).map(String::valueOf).collect(Collectors::toList)
    }
}

intellij告诉我:

intellij tell me :

收藏家<字符串,A,R> 不是功能界面

但是当我按如下方式修改代码时,一切正常,我不知道知道原因吗?

but when i modify the code as follows, everything is ok, i don't know why?

public class Test {
    public static void main(String[] args) {

        Stream.of(1,2,3).map(String::valueOf).collect(Collectors.<String>toList)
    }
}


推荐答案

第一种语法非法的原因是方法签名隐含的目标类型&mdash ; Stream.collect(收集器)—是收集器收集器有多个抽象方法,因此它不是一个功能接口,并且不能有 @FunctionalInterface 注释。

The reason that the first syntax is illegal is that the target type implied by the method signature—Stream.collect(Collector)—is a Collector. Collector has multiple abstract methods, so it isn't a functional interface, and can't have the @FunctionalInterface annotation.

方法引用,如 Class :: function object :: method 只能分配给功能接口类型。由于收集器不是功能接口,因此不能使用方法引用将参数提供给 collect(收集器)

Method references like Class::function or object::method can only be assigned to functional interface types. Since Collector is not a functional interface, no method reference can be used to supply the argument to collect(Collector).

相反,调用 Collectors.toList()作为函数。显式< String> 类型参数是不必要的,并且您的工作示例在最后没有括号时将无法工作。这将创建一个收集器实例,可以传递给 collect()

Instead, invoke Collectors.toList() as a function. The explicit <String> type parameter is unnecessary, and your "working" example won't work without parentheses at the end. This will create a Collector instance that can be passed to collect().

这篇关于java 8 Collector&lt; String,A,R&gt;不是功能界面,谁能说出原因?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 02:19