Java 8 Collector <String, A, R> is not a functional interface, who can understand why?

The following code:

public class Test { public static void main(String[] args) { Stream.of(1,2,3).map(String::valueOf).collect(Collectors::toList) } } 

intellij tell me:

Collector<String, A, R> not a functional interface

but when I change the code as follows, everything is fine, 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) } } 
+6
source share
2 answers

The reason the first syntax is illegal is because the target type, the implied method signature - Stream.collect(Collector) - is Collector . Collector has several abstract methods, so it is not a functional interface and cannot contain the @FunctionalInterface annotation.

object::method references, such as Class::function or object::method , can only be assigned to function interface types. Since Collector not a functional interface, a method reference cannot be used to refer to collect(Collector) .

Instead, call Collectors.toList() as a function. An explicit parameter of type <String> not needed, and your β€œworking” example will not work without parentheses at the end. This will create an instance of Collector , which can be passed to collect() .

+6
source

The Collector interface has several methods ( combiner() , finisher() , supplier() , accumulator() ) require implementation, so it cannot be a functional interface that can have only one method with no default implementation.

I do not see how your question is related to the attached code.

+3
source

All Articles