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
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
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
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!
Other Java Articles you may like
50+ Java Collections Interview Questions for Beginners and Experienced Programmers
Java Collection and Generic are a very important topic for Java Interviews. They also present some of the hardest…
The 2022 Java Programmer RoadMap
An illustrated guide to becoming a Java Developer in 2022 with links to relevant courses