Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does java stream.count() return a long?

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?

like image 431
NDavis Avatar asked Jun 20 '17 19:06

NDavis


People also ask

Why is stream count long?

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.

What does count () do in Java?

The counting() method of the Java 8 Collectors class returns a Collector accepting elements of type T that counts the number of input elements.

What does stream () return?

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.


2 Answers

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

like image 180
Sergey Kalinichenko Avatar answered Oct 16 '22 16:10

Sergey Kalinichenko


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?

like image 21
Eugene Avatar answered Oct 16 '22 18:10

Eugene