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
Java Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java Interview Questions and Answers Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Java OOP(Object Oriented Programming) Concepts Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Arrays in Java Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
Inheritance in Java Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
13 min read
Collections in Java Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Java Exception Handling Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runt
10 min read
Java Programs - Java Programming Examples In this article, we will learn and prepare for Interviews using Java Programming Examples. From basic Java programs like the Fibonacci series, Prime numbers, Factorial numbers, and Palindrome numbers to advanced Java programs.Java is one of the most popular programming languages today because of its
8 min read
Java Interface An Interface in Java programming language is defined as an abstract type used to specify the behaviour of a class. An interface in Java is a blueprint of a behaviour. A Java interface contains static constants and abstract methods. Key Properties of Interface:The interface in Java is a mechanism to
12 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read