Skip to content

Instantly share code, notes, and snippets.

@gdejohn
Last active February 1, 2026 00:52
Show Gist options
  • Select an option

  • Save gdejohn/8293321 to your computer and use it in GitHub Desktop.

Select an option

Save gdejohn/8293321 to your computer and use it in GitHub Desktop.
straightforward five-card poker hand comparison
package poker;
public record Card(Rank rank, Suit suit) {
public enum Rank {
TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE
}
public enum Suit {
DIAMONDS, CLUBS, HEARTS, SPADES
}
}
package poker;
public enum Category {
HIGH_CARD, ONE_PAIR, TWO_PAIR, THREE_OF_A_KIND, STRAIGHT, FLUSH, FULL_HOUSE, FOUR_OF_A_KIND, STRAIGHT_FLUSH
}
package poker;
import java.util.*; // Arrays, Comparator, Set
import java.util.function.Function;
import poker.Card.Rank;
import static java.util.Comparator.*; // comparing, naturalOrder
import static java.util.stream.Collectors.*; // counting, groupingBy
import static poker.Card.Rank.*;
public record Hand(Category category, Rank... ranks) implements Comparable<Hand> {
public static Hand evaluate(Set<Card> cards) {
assert cards.size() == 5;
var counts = cards.stream().collect(groupingBy(Card::rank, counting()));
Function<Rank,Long> count = counts::get;
var order = comparing(count).thenComparing(naturalOrder()).reversed();
Rank[] ranks = counts.keySet().stream().sorted(order).toArray(Rank[]::new);
var straight = ranks[0].ordinal() - ranks[ranks.length - 1].ordinal() == 4;
var wheel = ranks[0] == ACE && ranks[1] == FIVE;
var flush = cards.stream().map(Card::suit).distinct().count() == 1;
return counts.get(ranks[0]) == 4 ? new Hand(QUADS, ranks)
: ranks.length == 2 ? new Hand(FULL_HOUSE, ranks)
: counts.get(ranks[0]) == 3 ? new Hand(TRIPS, ranks)
: ranks.length == 3 ? new Hand(TWO_PAIR, ranks)
: ranks.length == 4 ? new Hand(PAIR, ranks)
: straight ? new Hand(flush ? STRAIGHT_FLUSH : STRAIGHT, ranks[0])
: wheel ? new Hand(flush ? STRAIGHT_FLUSH : STRAIGHT, FIVE)
: new Hand(flush ? FLUSH : HIGH_CARD, ranks);
}
@Override
public int compareTo(Hand hand) {
return Comparator.comparing(Hand::category)
.thenComparing(Hand::ranks, Arrays::compare)
.compare(this, hand);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment