Reputation: 846
From https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html#counting--:
public static <T> Collector<T,?,Long> counting()
Returns a
Collector
accepting elements of typeT
that counts the number of input elements. If no elements are present, the result is 0.Implementation Requirements:
This produces a result equivalent to:
reducing(0L, e -> 1L, Long::sum)
Why does this Collector collect into a long? Is it because it can be optimized on various platforms where typedef size_t uint64_t
? Or am I missing something? Is there a practical use for a Stream with more than Integer.MAX_VALUE
items?
Upvotes: 0
Views: 529
Reputation: 167
If the number of elements are more than Integer.MAX value then adding up will wrap on the int max value, which will make total sum value (number of elements) wrong.
We generally write results in long where the result involves addition of elements.
In short, provided long return type to give support for all cases (number of elements less than Integer.MAX and greater than Integer.MAX both).
Upvotes: 3