Java Programming Tutorials

Java programming tutorials with many code examples!

Java 8 Comparators with Method References

Java 8 Comparators with Method References in action. We mix Java 8 static and default methods with method references to sort objects by multiple fields using chained Comparators!

Sample class with multiple fields to compare

We’ll apply Java 8 Composite Comparators on the following simple class:

class Player {
    private final String name;
    private final int score;

    public Player(String name, int score) {
        this.name = name;
        this.score = score;
    }

    public String getName() {
        return name;
    }

    public int getScore() {
        return score;
    }
}

Java 8 Comparators in action

In this program we create sample Players with scores picked randomly from very small subset to have them repeated. It will allow us to test sorting by names, when the scores are the same.

package com.farenda.java.util;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Random;

class Player {
  // cut for brevity (see above)
}

public class Java8Comparators {

    public static void main(String[] args) {
        Random rand = new Random();

        // Create sample players:
        List<Player> players = new ArrayList<>();
        for (int i = 1; i <= 10; ++i) {
            int score = rand.nextInt(10);
            String name = "Player " + i;
            players.add(new Player(name, score));
        }

        // Sort them by high scores, then alphabetically by names:
        players.sort(
                Comparator.comparing(Player::getScore).reversed()
                        .thenComparing(Player::getName));

        // Print the high scores:
        System.out.println("Score |   Name");
        for (Player player : players) {
            System.out.printf("%5d | %8s%n",
                    player.getScore(), player.getName());
        }
    }
}

In the above code we’ve used a few Java 8 features:

  • List.sort(Comparator) default method
  • Comparator.comparing(Function) static factory method to create a Comparator based on Java 8 Method Reference to a function that will extract sorting key; equally well we could have used Comparator.comparingIng(ToIntFunction) here, because score is an int;
  • Comparator.reverse() and Comparator.thenComparing(Function) default methods to chain comparators.

Simple and beautiful! :-)

Anyway, the above code produces the following output:

Score |   Name
    7 | Player 2
    7 | Player 7
    6 | Player 1
    4 | Player 10
    3 | Player 8
    2 | Player 3
    1 | Player 5
    1 | Player 9
    0 | Player 4
    0 | Player 6

Notice how players, who have the same score, are sorted by their names.

Share with the World!