1. Introduction
In Java, the Comparator interface is used to order the objects of user-defined classes. If you want to order objects in a specific sequence (either ascending or descending), Comparator can be very helpful. In this tutorial, we will see how to sort a list of integers in descending order using the Comparator interface.
2. Program Steps
1. Create a list of integers.
2. Define a Comparator that will order the integers in descending order.
3. Use the Collections.sort() method to sort the list using the defined Comparator.
4. Display the sorted list.
3. Code Program
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class DescendingOrderComparator {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(5);
numbers.add(15);
numbers.add(3);
numbers.add(12);
System.out.println("Original list: " + numbers);
// Sort using comparator in descending order
Collections.sort(numbers, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2 - o1; // Swap positions for descending order
}
});
System.out.println("Sorted list (descending): " + numbers);
}
}
Output:
Original list: [10, 5, 15, 3, 12] Sorted list (descending): [15, 12, 10, 5, 3]
4. Step By Step Explanation
1. We begin by initializing an ArrayList and populating it with some integer values.
2. Using the Comparator interface, we define an anonymous inner class that implements the compare method. This method determines the order of the objects in the list.
3. Inside the compare method, we return the result of subtracting o1 from o2. This inversion ensures that the numbers are sorted in descending order. If o1 is greater than o2, it will return a positive value, placing o1 before o2 in the list.
4. Using the Collections.sort() method, we sort our list according to the ordering defined by our Comparator.
5. Finally, we print out the original and sorted list to view the results.
By using the Comparator interface, we gain fine-grained control over the ordering of our list, allowing us to sort it in any way we see fit.