Published in


How to count a billion random ints using Eclipse Collections

Learn how to build a primitive Bag from a primitive Stream in Java.

Code generates a billion random ints between 1 and 10 and counts them in an IntBag. Prints top and bottom 5.

The Output:

Top 5 random ints between 1 and 10 (top line). Bottom 5 random ints between 1 and 10 (bottom line).

Eclipse Collections has several primitive collection types which I wrote about in the following blog in August 2021.

An IntBag is a primitive Bag which is useful for counting int values. You can initialize an IntBag directly from an IntStream using a specialized withAll method as seen in the example above. An IntBag has topOccurrences and bottomOccurrences methods which can be quite handy. There are also DoubleBag and LongBag types which can be initialized directly from a DoubleStream and LongStream using their corresponding withAll methods available through DoubleBags and LongBags factory classes.

The withAll methods that take primitive Streams as parameters appeared in the Eclipse Collections 9.0 release. If you prefer, there are also equivalent methods named ofAll. If you want to understand why there are both withAll and ofAll methods that do the same thing, the following blog will help explain.

Thank you for reading! Enjoy!

I am the creator of and a Committer for the Eclipse Collections OSS project which is managed at the Eclipse Foundation. Eclipse Collections is open for contributions.

Other Java Articles you may like



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Donald Raab

Donald Raab

Java Champion. Creator of the Eclipse Collections OSS Java library ( Inspired by Smalltalk. Opinions are my own.