How to create a deck of cards using Eclipse Collections

Donald Raab
Javarevisited
Published in
2 min readSep 22, 2022

A fun example using Eclipse Collections with Java enums and records

Photo by Jack Hamilton on Unsplash

The Cartesian Product of Rank and Suit

If we have an enum of Rank and enum of Suit, it is trivial to create a Card type using Java Records. It is also trivial to create a deck of cards using the cartesianProduct method from Eclipse Collections. We can assert that we get 52 instances of Card total. We can group the cards by Suit and Rank and assert that we get 4 Suits and 13 Ranks. We can also shuffle the cards three times and deal five hands of five cards each using an MutableStack and IntInterval. Finally, we can print the five hands of cards.

cartesianProduct, groupBy, toList, shuffleThis, toStack, IntInterval, collect, multi-pop, toSortedList & forEach

The following is the final output.

Dealing five hands of five cards each

I used Java 17 to write this code. Is Java still too verbose? You decide. I think Java is getting better every 6 months with each new release. 😀

If you’d like to experiment with creating your own deck of cards using the newest features of Java, you can check out this kata here.

Thank you for reading!

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

--

--

Donald Raab
Javarevisited

Java Champion. Creator of the Eclipse Collections OSS Java library (https://github.com/eclipse/eclipse-collections). Inspired by Smalltalk. Opinions are my own.