문제

Currently learning Java so this may be a question resulting from lack of understanding of Java (while also learning Streams API)

In the declarations of function I often see two templated types for the return values. For instance below we have <T,U> and also Collector<T,?,U>. How should I read this? That it returns one of two possible types? This just looks odd since I've always thought functions return one type of data.

public static <T,U> Collector<T,?,U> reducing(U identity,
                                          Function<? super T,? extends U> mapper,
                                          BinaryOperator<U> op)
도움이 되었습니까?

해결책

That signifies that the itself method is generic. It allows creation of static utility methods or use generic variables without needing to include those parameters in the whole class.

in order the parts are:

  • public: visibility

  • static: it's a static method

  • <T,U>: it's a generic method with parameters T and U

  • Collector<T,?,U>: returns a Collector<T,?,U>

  • reducing: the name of the method

  • (U identity,Function<? super T,? extends U> mapper,BinaryOperator<U> op): the parameter list

To call the method and specify the parameters you can do Collectors.<Foo1,Foo2>reducing(...)

다른 팁

<T,U> is the method declaring that it uses the generic types T and U.

T is the type of the input elements U is the type of the mapped values

The return type is a Collector<T,?,U>

Taken from the javadoc.

The best place to start is with is the oracle lambda tutorial, which touches on aggregation and generics.

Then look at aggregation, and specifically, more info on reduction in an oracle tutorial

(disclaimer: opinion based) This is probably the most horrible thing you could do when starting with java. The aggregation framework uses the most mind mangling generics and lambdas.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 softwareengineering.stackexchange
scroll top