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
?
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.
The counting() method of the Java 8 Collectors class returns a Collector accepting elements of type T that counts the number of input elements.
Streams don't change the original data structure, they only provide the result as per the pipelined methods. Each intermediate operation is lazily executed and returns a stream as a result, hence various intermediate operations can be pipelined. Terminal operations mark the end of the stream and return the result.
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With