Reputation: 1227
Why doesn't a stream.count()
return an int
?
I understand that I can easily convert the long
to an int
by casting,
return (int) players.stream().filter(Player::isActive).count();
but why would a java stream.count()
return a long
instead of an int
?
Upvotes: 43
Views: 40768
Reputation: 241
This statement
players.stream().filter(Player::isActive).count();
is equivalent to:
players.stream().filter(Player::isActive).collect(Collectors.counting());
This still returns a long
because Collectors.counting()
is implemented as
reducing(0L, e -> 1L, Long::sum)
Returning an int
can be accomplished with the following:
players.stream().filter(Player::isActive).collect(Collectors.reducing(0, e -> 1, Integer::sum));
This form can be used in groupingBy
statement
Map<Player, Integer> playerCount = players.stream().filter(Player::isActive).collect(Collectors.groupingBy(Function.identity(), Collectors.reducing(0, e -> 1, Integer::sum)));
Upvotes: 24
Reputation: 726539
When Java came out in early 1996, common PCs had 8 to 16 Mb of memory. Since both arrays and collections were closely tied to memory size, using int
to represent element counts seemed natural, because it was sufficient to address an array of int
s that is 4Gb in size - a size gigantic even for hard drives in 1996, let alone RAM. Hence, using long
instead of int
for collection sizes would seem wasteful at the time.
Although int
size may be a limiting factor at times, Java designers cannot change it to long
, because it would be a breaking change.
Unlike Java collections, streams could have potentially unlimited number of elements, and they carry no compatibility considerations. Therefore, using long
with its wider range of values seems like a very reasonable choice.
Upvotes: 25
Reputation: 120848
Well simply because it's the biggest 64-bit primitive value that java has. The other way would be two counts:
countLong/countInt
and that would look really weird.
int
fits in a long
, but not the other way around. Anything you want to do with int you can fit in a long, so why the need to provide both?
Upvotes: 23