Sort an Array in Java using Comparator
Last Updated : 24 Mar, 2025
A Comparator is an object that can be used to compare two objects and determine their order. We can use a Comparator to sort a list of objects in any order we can choose, not just in ascending order.
Examples:
Array(Ascending Order):
Input: arr = (4, 2, 5, 1, 3)
Output: [1, 2, 3, 4, 5]
Array(Descending Order):
Input: arr = (4, 2, 5, 1, 3)
Output: [5, 4, 3, 2, 1]
Strings(Ascending Order):
Input: str = ("Jan", "Tommy", "Jo", "Adam")
Output: [Jo, Jan, Adam, Tommy]
Strings(Ascending Order):
Input: str = ("Jan", "Tommy", "Jo", "Adam")
Output: [Tommy, Adam, Jan, Jo]
Algorithm
- Implement the Comparator interface and override the compare method.
- In the compare method, compare the two objects and return a negative integer if the first object is less than the second, a positive integer if the first object is greater than the second, or 0 if they are equal.
- To sort an array using the comparator first we convert the array into the list, call the sort method on the list and pass an instance of the comparator as an argument.
Below are the implementations of the above algorithm for strings and integers (Ascending and Descending both).
For Array (Ascending Order)
Java // Java program to sort list of integers // using Comparator in Java // Ascending Order according to length import java.util.Comparator; import java.util.List; import java.util.ArrayList; import java.util.Arrays; class IntegerAscendingComparator implements Comparator<Integer> { @Override public int compare(Integer x, Integer y) { return x - y; } } public class Geeks { public static void main (String[] args) { // Create an array of integers Integer arr[] = {10, 3, 5, 7, 6}; // Converting the array into a list List<Integer> numbers = new ArrayList<>(Arrays.asList(arr)); // List<Integer> numbers = Arrays.asList(4, 2, 5, 1, 3); numbers.sort(new IntegerAscendingComparator()); System.out.println(numbers); } }
For Array (Descending Order)
Java // Java program to sort list of integers // using Comparator in Java // Descending Order according to length import java.util.Comparator; import java.util.List; import java.util.Arrays; public class DescendingComparator implements Comparator<Integer> { @Override public int compare(Integer i1, Integer i2) { return i2 - i1; } public static void main(String[] args) { // Ceating an array of Integers Integer[] arr = {5, 20, 10, 3, 15}; // Converting Integer array to list List<Integer> list = Arrays.asList(arr); // Sorting list of integers in descending order List<Integer> numbers = list; numbers.sort(new DescendingComparator()); System.out.println(numbers); } }
For Strings (Ascending Order)
Java // Java program to sort list of strings // using Comparator in Java // Ascending Order according to length import java.util.Comparator; import java.util.List; import java.util.Arrays; public class StringLengthComparator implements Comparator<String> { @Override public int compare(String s1, String s2) { return s1.length() - s2.length(); } public static void main (String[] args) { List<String> names = Arrays.asList("Jan", "Tommy", "Jo", "Adam"); names.sort(new StringLengthComparator()); System.out.println(names); } }
Output[Jo, Jan, Adam, Tommy]
For Strings (Descending Order)
Java // Java program to sort list of strings // using Comparator in Java // Descending Order according to length import java.util.Comparator; import java.util.List; import java.util.Arrays; public class StringComparator implements Comparator<String> { @Override public int compare(String s1, String s2) { return s2.length() - s1.length(); } public static void main(String[] args) { // Creating an array of strings String[] arr = {"GeeksforGeeks", "I", "from", "am"}; // Converting the array to a list List<String> list = Arrays.asList(arr); // Sorting the list using the custom Comparator list.sort(new StringComparator()); // Displaying the sorted list System.out.println(list); } }
Output[GeeksforGeeks, from, am, I]
Sorting Using Custom Comparator
We can sort an array using a custom comparator by using the Arrays.sort() method along with a Comparator.
Java // Java program to demonstrate // Custom Sorting using Comparator // with method reference import java.util.Arrays; import java.util.Comparator; public class Geeks { // Class to store the details of people static class p { String name; int age; p(String name, int age) { this.name = name; this.age = age; } @Override public String toString() { return name + " (" + age + ")"; } } public static void main(String[] args) { p[] people = { new p("Happy", 30), new p("Shivansh", 25), new p("Divyansh", 35) }; // Sort by age using method reference Arrays.sort(people, Comparator.comparingInt(p -> p.age)); System.out.println("Sorted by age: " + Arrays.toString(people)); // Sort by name using method reference Arrays.sort(people, Comparator.comparing(p -> p.name)); System.out.println("Sorted by name: " + Arrays.toString(people)); } }
OutputSorted by age: [Shivansh (25), Happy (30), Divyansh (35)] Sorted by name: [Divyansh (35), Happy (30), Shivansh (25)]
Explanation: The comparator that we provided has a time complexity of O(n log(n)), where n is the number of elements in the list. This is because the sort method uses a comparison-based algorithm (such as merge sort or quick sort) to sort the list, and the time complexity of these algorithms is O(n * log(n)). The space complexity of the comparator is O(1) since it does not allocate any additional memory beyond the comparator object itself.
Similar Reads
How to sort an Array of Strings in Java
Array Of StringsTo sort an array of strings in Java, we can use Arrays.sort() function. Java Code // A sample Java program to // sort an array of strings // in ascending and descending // orders using Arrays.sort(). import java.util.Arrays; import java.util.Collections; // Driver Class public class
3 min read
Compare Two Arrays in Java
In Java, comparing two arrays can be confusing, because the "==" operator only checks if the two arrays point to the same memory location. To compare the contents of arrays, we need to use other methods like Arrays.equals() or Arrays.deepEquals(). Example: Let us see in the below example, how to com
5 min read
Stream sorted (Comparator comparator) method in Java
Stream sorted(Comparator comparator) returns a stream consisting of the elements of this stream, sorted according to the provided Comparator. For ordered streams, the sort method is stable but for unordered streams, no stability is guaranteed. It is a stateful intermediate operation i.e, it may inco
3 min read
Java Comparable vs Comparator
In Java, both Comparable and Comparator interfaces are used for sorting objects. The main difference between Comparable and Comparator is: Comparable: It is used to define the natural ordering of the objects within the class.Comparator: It is used to define custom sorting logic externally.Difference
5 min read
Arrays.sort() in Java
The Arrays.sort() method is used for sorting the elements in an Array. It has two main variations: Sorting the entire array (it may be an integer or character array) Sorting a specific range by passing the starting and ending indices.Below is a simple example that uses the sort() method to arrange a
6 min read
Sort a String in Java (2 different ways)
The string class doesn't have any method that directly sorts a string, but we can sort a string by applying other methods one after another. The string is a sequence of characters. In java, objects of String are immutable which means a constant and cannot be changed once created. Creating a String T
6 min read
How to Sort an Arrays of Object using Arrays.sort()
To sort the array of objects in both ascending and descending order in Java, we can use the Arrays.sort() method with the Comparator. In this article, we will learn how to sort an array of objects using Arrays.sort(). Sorting an Array of ObjectWith Array of Object what it really means is an array st
3 min read
PriorityQueue comparator() Method in Java
The java.util.PriorityQueue.comparator() method shares an important function of setting and returning the comparator that can be used to order the elements in a PriorityQueue. The method returns a null value if the queue follows the natural ordering pattern of the elements.Syntax: comp_set = (Priori
2 min read
PriorityBlockingQueue comparator() method in Java
The comparator() method of PriorityBlockingQueue returns the comparator that can be used to order the elements in a PriorityBlockingQueue. The method returns null value if the queue follows the natural ordering pattern of the elements. Syntax: public Comparator<? super E> comparator() Returns:
2 min read
Short compare() method in Java
The compare() method of Short class is used to compare two primitive short values for numerical equality. As it is a static method therefore it can be used without creating any object of Short. Syntax: public static int compare(short x, short y) Parameters: This method accepts two parameters: x: whi
2 min read