How to create a deck of cards using Eclipse Collections
A fun example using Eclipse Collections with Java enums and records
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.
The following is the final output.
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.