Javarevisited
Published in

Javarevisited

How to create a deck of cards using Eclipse Collections

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

--

--

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 (http://www.eclipse.org/collections/). Inspired by Smalltalk. Opinions are my own.