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

别来无恙 提交于 2019-12-01 16:20:38

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!