Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

The follow 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> is not a functional interface

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());
    }
}
like image 548
Rollen Holt Avatar asked Aug 19 '15 11:08

Rollen Holt


2 Answers

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.

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).

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().

like image 57
erickson Avatar answered Oct 28 '22 07:10

erickson


The Collector interface has multiple methods (combiner(), finisher(), supplier(), accumulator()) the require an implementation, so it can't be a functional interface, which can have only one method with no default implementation.

I don't see how your question is related to the attached code.

like image 33
Eran Avatar answered Oct 28 '22 07:10

Eran