java 8 Collector is not a functional interface, who can tell why?

前端 未结 2 1380
北海茫月
北海茫月 2021-01-11 23:24

The follow code:

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


        
2条回答
  •  生来不讨喜
    2021-01-12 00:15

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

提交回复
热议问题