0

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)
  • 3
    These are generics. Look up the Java generics guide, which should explain everything – raptortech97 Nov 3 '14 at 22:08
  • Thanks all. I should have caught this. I'm used to seeing something like reducing<T,U> – user154950 Nov 4 '14 at 11:02
1

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

1

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

  • I think you might mean lambda, not lambada... – raptortech97 Nov 4 '14 at 2:43
  • you are totally right :) – tom Nov 4 '14 at 7:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy