Sort an Array in Java using Comparator
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 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);
}
}
// 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> {
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 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);
}
}
// 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> {
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 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);
}
}
// 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> {
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 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);
}
}
// 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> {
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 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));
}
}
// 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;
}
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.