Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Stream sorted (Comparator comparator) method in Java
Next article icon

Sort an Array in Java using Comparator

Last Updated : 24 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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

  1. Implement the Comparator interface and override the compare method.
  2. 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.
  3. 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);      } } 

Output
[3, 5, 6, 7, 10] 

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);     } } 

Output
[20, 15, 10, 5, 3] 

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));     } } 

Output
Sorted 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.


Next Article
Stream sorted (Comparator comparator) method in Java
author
susobhanakhuli
Improve
Article Tags :
  • Java
  • Technical Scripter
  • Technical Scripter 2022
  • Java-Array-Programs
Practice Tags :
  • Java

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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences