Understand declaration of a terminal operation method

67 Views Asked by At

Usually, a method's declaration shows its return type, method full path, and parameters. But when I look at method java.util.stream.Stream.collect I am confused.

It seems that the method has two return types:

<List<Integer>, Object> List<Integer> java.util.stream.Stream.collect(Collector<? super Integer, Object, List<Integer>> collector)

I understand that its real return type is List<Integer>, but what does <List<Integer>, Object> mean? Why is it one space before List<Integer> and why is its key(if it is a map?) the same as the real return type?

1

There are 1 best solutions below

1
On BEST ANSWER

Have a look at the declaration of the method:

public interface Stream<T> extends BaseStream<T, Stream<T>> {
    ...
    /* ...
     * @param <R> the type of the result
     * @param <A> the intermediate accumulation type of the {@code Collector}
     * ...
     */
    <R, A> R collect(Collector<? super T, A, R> collector);
    ...
}

As Nathan pointed out in the comments, the <R, A> denotes generic type parameters. These will be inferred by the Java compiler as long as it is unambiguous. In your case R was inferred to List<Integer> and A to Object. You can read here about generic methods.