'Sort a list of enums by multiple criteria

I have the following enum:

public enum Card {
    /**
     * blue cards
     */
    B_0_5_1(0, GameColor.BLUE, 5),
   //...
    /**
     * the color of the card
     */
    public final GameColor gameColor;
    /**
     * the number of the card
     */
    public final int number;
    /**
     * the number of fields the oracle priestess can go with this card
     */
    public final int oraclePriestessFields;

    /**
     * creates a new card
     *
     * @param number                the number of the card
     * @param gameColor             the color of the card
     * @param oraclePriestessFields the number of fields for the oracle priestess
     */
    private Card(int number, GameColor gameColor, int oraclePriestessFields) {
        this.gameColor = gameColor;
        this.oraclePriestessFields = oraclePriestessFields;
        this.number = number;
    }

    @Override
    public String toString() {
        return "Card{" +
                "gameColor=" + gameColor +
                ", number=" + number +
                ", oraclePriestessFields=" + oraclePriestessFields +
                "} " + super.toString();
    }
    public String prettyPrint() {
        return String.format("%s, (%d/%d)", gameColor.getColor().substring(0,2), number, oraclePriestessFields);
    }
}

I now have a list of cards. I want to sort this list first by the color and then by the value of the card, so that the cards are grouped by the color and then sorted by value.

I tried to achieve this using my own Comparator following this https://howtodoinjava.com/java8/sort-stream-multiple-fields/ tutorial, but somehow the compiler doesn't like my attempt:

Comparator<Card> c = Comparator.comparing(c ->c.gameColor).thenComparingInt(c->c.number);

Can you help me out here?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source