Java Comparator naturalOrder() Method
Example
Sort a list in natural order (alphabetically):
import java.util.ArrayList;
import java.util.Comparator;
public class Main {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
cars.sort(Comparator.naturalOrder());
System.out.println(cars);
}
}
Definition and Usage
The naturalOrder() method returns a comparator that sorts objects in their natural order. The natural order is the order that the class itself defines with its compareTo() method: strings are sorted alphabetically (A to Z), and numbers from small to large.
Use it when a method needs a comparator, but you want the normal order. cars.sort(Comparator.naturalOrder()) gives the same result as Collections.sort(cars).
Tip: Use reverseOrder() to sort in the opposite order.
Syntax
public static <T extends Comparable<? super T>> Comparator<T> naturalOrder()
T refers to the data type of the objects to sort. It must be a type that implements Comparable, like String or Integer.
Parameter Values
None.
Technical Details
| Returns: | A Comparator that sorts objects in their natural order. |
|---|
Related Pages
Java Advanced Sorting Tutorial
Java Lambda Expressions Tutorial
❮ Comparator Methods