AI Hints
Home›Java Tutorial›Sorting with Comparator, Removing While Looping, Practice: Word Counter
Java · Lesson 88 of 120

Sorting with Comparator

Sort your way.

⏱ 2 min read▶ Video at 1:51:25🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Collections dot sort puts a list in natural order. Numbers smallest first, words alphabetically. A comparator lets you sort any way you like.

  • Natural order
  • Or your own order
  • With a Comparator

Sorting strings

Importing java dot util, star, brings in the whole package. Collections dot sort sorts alphabetically. Reverse order flips it. Comparing, with string colon colon length, sorts by length. The double colon is a method reference. We'll explain it in module twelve. Then comparing breaks ties, alphabetically. Run it. Each line shows a different order. Notice fig, and kiwi, swap places in the last line.

Main.javajava
import java.util.*;
public class Main {
    public static void main(String[] args) {
        List<String> fruit = new ArrayList<>(List.of("pear", "fig", "banana", "kiwi"));
        Collections.sort(fruit);
        System.out.println("A to Z:     " + fruit);
        fruit.sort(Comparator.reverseOrder());
        System.out.println("Z to A:     " + fruit);
        fruit.sort(Comparator.comparing(String::length));
        System.out.println("By length:  " + fruit);
        fruit.sort(Comparator.comparing(String::length)
                             .thenComparing(Comparator.naturalOrder()));
        System.out.println("Then A-Z:   " + fruit);
    }
}
Output
A to Z:     [banana, fig, kiwi, pear]
Z to A:     [pear, kiwi, fig, banana]
By length:  [fig, pear, kiwi, banana]
Then A-Z:   [fig, kiwi, pear, banana]

Sorting objects

Here's a small record, Person, with a name and an age. Comparing person age sorts by age. Reversed flips that, and then comparing name breaks ties. Run it. Youngest first. Then oldest first, with Mia before Zoe, because they're both thirty one.

Main.javajava
import java.util.*;
public class Main {
    record Person(String name, int age) {}

    public static void main(String[] args) {
        List<Person> people = new ArrayList<>(List.of(
            new Person("Zoe", 31), new Person("Adam", 25), new Person("Mia", 31)));
        people.sort(Comparator.comparing(Person::age));
        System.out.println(people);
        people.sort(Comparator.comparing(Person::age).reversed()
                              .thenComparing(Person::name));
        System.out.println(people);
    }
}
Output
[Person[name=Adam, age=25], Person[name=Zoe, age=31], Person[name=Mia, age=31]]
[Person[name=Mia, age=31], Person[name=Zoe, age=31], Person[name=Adam, age=25]]

Comparator recipes

Comparing picks the value to sort by. Reversed flips the order. Then comparing adds a tie breaker. You can chain as many as you need.

keyvalue
Sort byComparator.comparing(X::field)
Flip…reversed()
Tie-break…thenComparing(…)
NaturalCollections.sort(list)

Summary

Collections dot sort uses natural order. A comparator sorts by any field, can be reversed, and can break ties. Next, removing items safely, while looping.

Key takeaways
  • Collections.sort
  • Comparator.comparing
  • reversed, thenComparing
Next up: Removing While Looping — the safe way