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;
public static <T extends Comparable<? super T>> Comparator<T> naturalOrder()
This method takes no parameters.
The method returns a Comparator
.
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));}}
strings
.strings
array.strings
array in the natural order.strings
array.