The List.sort()
method was introduced in Java 8. This method sorts the elements of the list on the basis of the given Comparator
. If no comparator is provided, it will use the natural ordering of the elements (only if the elements are Comparable
).
Let’s take a look at an example where we sort a list of integers in ascending order:
package org.kodejava.util;
import java.util.ArrayList;
import java.util.List;
public class ListSortExample {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
numbers.add(3);
numbers.add(1);
numbers.add(4);
numbers.add(1);
numbers.add(5);
// Use sort() to sort the numbers in ascending order
numbers.sort(null);
System.out.println(numbers);
}
}
Outputs:
[1, 1, 3, 4, 5]
You can also pass a Comparator
to List.sort()
. Here’s an example where we sort a list of strings by their length:
package org.kodejava.util;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class ListSortOtherExample {
public static void main(String[] args) {
List<String> words = new ArrayList<>();
words.add("rat");
words.add("elephant");
words.add("cat");
words.add("mouse");
// Comparator for comparing string lengths
Comparator<String> lengthComparator = (s1, s2) -> s1.length() - s2.length();
// Use sort() to sort the words by their length
words.sort(lengthComparator);
System.out.println(words);
}
}
Outputs:
[rat, cat, mouse, elephant]
In this case, the Comparator
is a lambda expression that computes the difference in length between two strings. The List.sort()
method uses this Comparator
to determine the ordering of the strings in the list.