How to use Comparator with Array in Java?

In the following example, we’ve defined two custom comparators: AscendingComparator and DescendingComparator. These comparators implement the Comparator interface and override the compare method to provide the desired comparison logic.

We then use these comparators to sort an array of integers in both ascending and descending order using the Arrays.sort() method. The output will show the array sorted first in ascending order and then in descending order.

Now let’s see the practical example below:

import java.util.Arrays;
import java.util.Comparator;

public class ArrayComparatorExample {
    public static void main(String[] args) {
        // Sample array of integers
        Integer[] numbers = { 5, 2, 8, 1, 3 };

        // Using a Comparator to sort the array in ascending order
        Arrays.sort(numbers, new AscendingComparator());

        System.out.println("Array sorted in ascending order: " + Arrays.toString(numbers));

        // Using a Comparator to sort the array in descending order
        Arrays.sort(numbers, new DescendingComparator());

        System.out.println("Array sorted in descending order: " + Arrays.toString(numbers));
    }
}

// Comparator for ascending order
class AscendingComparator implements Comparator<Integer> {
    @Override
    public int compare(Integer o1, Integer o2) {
        return o1.compareTo(o2);
    }
}

// Comparator for descending order
class DescendingComparator implements Comparator<Integer> {
    @Override
    public int compare(Integer o1, Integer o2) {
        return o2.compareTo(o1);
    }
}

Output:

Array sorted in ascending order: [1, 2, 3, 5, 8]
Array sorted in descending order: [8, 5, 3, 2, 1]
Sharing Is Caring: