Trusted answers to developer questions

What is the Comparator.naturalOrder method in Java?

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.

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 strings array.
  • Line 14: We sort the strings array in the natural order.
  • Line 17: We print the sorted strings array.

RELATED TAGS

java
comparator
naturalorder
Did you find this helpful?