Comparator with lambda
- Java course
- Intermediate
- Lesson 104/116
- 5 min
Learn sorting with Comparator.comparing.
Comparator with a lambda
The modern way to sort a list is to give sort a Comparator lambda. names.sort((a, b) -> a.length() - b.length()); sorts names by length. A Comparator takes two parameters; it returns negative, zero or positive.
For ascending order write a - b; for descending write b - a. A more readable way is Comparator.comparingInt(String::length). This uses a method reference to make a field the sort key. To reverse, append .reversed().
Comparator.comparingInt
Comparator.comparingInt(String::length) makes a field a sort key. The method reference String::length is the key extractor function. This is more readable than the (a, b) -> a.length() - b.length() lambda.
To sort by multiple keys use .thenComparing. For example first by length then alphabetically: Comparator.comparingInt(String::length).thenComparing(s -> s). For reverse order .reversed() flips the whole comparison.
Practice Sort names by length
Declare List<String> names = new ArrayList<>();; add "Mehmet", "Ayşe", "Alex". Sort ascending by length with names.sort((a, b) -> a.length() - b.length());. Print the result with names.forEach(System.out::println);.
Starter code
import java.util.List;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
// Declare List<String>, add 3 names, sort by length, print with forEach
}
}Sample solution
import java.util.List;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Mehmet");
names.add("Ayşe");
names.add("Alex");
names.sort((a, b) -> a.length() - b.length());
names.forEach(System.out::println);
}
}Expected output
Ayşe Alex Mehmet
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the length Comparator
names.sort((a, b) -> a.____() - b.length());
names.sort((a, b) -> a.length() - b.length());
Explanation: The length method returns the String length.
2 Match the Comparator lambda parts
| Term | Meaning |
|---|---|
(a, b) |
Two parameters |
-> |
Arrow token |
a.length() - b.length() |
Ascending |
b.length() - a.length() |
Descending |
3 What order does (a, b) -> a - b produce?
- Descending
- Ascending Correct answer
- Random
- Shuffled
Explanation: a - b sorts ascending; smaller values come first.