What is the Comparator.naturalOrder method in Java?
Overview
In Java, naturalOrder is a static method of the Comparator class. It’s used to return a Comparator that sorts the elements in the natural order.
The Comparator interface is defined in the java.util package. To import the Comparator interface, we use the following import statement:
import java.util.Comparator;
Syntax
public static <T extends Comparable<? super T>> Comparator<T> naturalOrder()
Parameters
This method takes no parameters.
Return value
The method returns a Comparator.
Example
import java.util.Arrays;import java.util.Comparator;public class Main{public static void main(String[] args) {String[] strings = {"hello", "educative", "edpresso"};System.out.println("Array before sorting: " + Arrays.toString(strings));Arrays.sort(strings, Comparator.naturalOrder());System.out.println("Array after sorting: " + Arrays.toString(strings));}}
Explanation
- Lines 1-2: We import the relevant classes and packages.
- Line 8: We define an array of strings called
strings. - Line 11: We print the
stringsarray. - Line 14: We sort the
stringsarray in the natural order. - Line 17: We print the sorted
stringsarray.