Sorting with Comparators in Java

In Java, you can use a comparator to specify a custom sorting order when sorting an array or list. A comparator is an object that implements the Comparator interface and provides a compare() method that compares two objects and returns an integer indicating their order.

Here is an example of how to use a comparator to sort a list of strings in descending order:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Main {
  public static void main(String[] args) {
    List<String> words = new ArrayList<>();
    words.add("apple");
    words.add("banana");
    words.add("cherry");

    // Create a comparator that sorts strings in descending order
    Comparator<String> comparator = new Comparator<String>() {
      @Override
      public int compare(String s1, String s2) {
        return s2.compareTo(s1);
      }
    };

    // Sort the list using the comparator
    Collections.sort(words, comparator);

    // Print the sorted list
    for (String word : words) {
      System.out.println(word);
    }
  }
}

This will output the following:

cherry banana apple

You can also use the sort() method of the Arrays class with a comparator to sort an array. The syntax is similar to the Collections.sort() method, with the comparator passed as an argument.

Here is an example of how to use a comparator to sort an array of integers in ascending order:

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

public class Main {
  public static void main(String[] args) {
    int[] numbers = { 5, 2, 7, 1, 3 };

    // Create a comparator that sorts integers in ascending order
    Comparator<Integer> comparator = new Comparator<Integer>() {
      @Override
      public int compare(Integer i1, Integer i2) {
        return i1.compareTo(i2);
      }
    };

    // Sort the array using the comparator
    Arrays.sort(numbers, comparator);

    // Print the sorted array
    for (int number : numbers) {
      System.out.println(number);
    }
  }
}

This will output the following:

1
2
3
5
7