Passing an argument to a Comparator – Java

I have a Comparator class and in its compareTo method it accesses a value from a HashMap. I was wondering if there was a way to pass the name of the key to the compareTomethod. Here is my code. For example in this code I want to pass "racesWon"

public static Comparator<Player> RacesWon = new Comparator<Player>() {
    public int compare(Player p1, Player p2) {
        Integer p1GamesWon = Integer.valueOf(p1.stats.get("racesWon"));
        Integer p2GamesWon = Integer.valueOf(p2.stats.get("racesWon"));
        return p2GamesWon.compareTo(p1GamesWon);
    }
};

Answer

There is a much simpler way of creating your comparator:

racesWon = Comparator.comparingInt(p -> Integer.valueOf(p.stats.get("racesWon")));

Of if you want a method that generates a comparator based on a given key:

Comparator<Player> getComparator(String key) {
    return Comparator.comparingInt(p -> Integer.parseInt(p.stats.get(key)));
}

Leave a Reply

Your email address will not be published. Required fields are marked *