1. Introduction
In Java, the Comparator interface provides a powerful mechanism to define custom ordering for collections of objects. Often, we need to sort data in ascending order, which is where the Comparator shines. In this tutorial, we’ll see how to sort a list of integers in ascending order using the Comparator interface.
2. Program Steps
1. Initialize a list of integers.
2. Create a Comparator that will arrange the integers in ascending order.
3. Utilize the Collections.sort() method to sort the list with the custom Comparator.
4. Print the sorted list to the console.
3. Code Program
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class AscendingOrderComparator {
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 ascending order
Collections.sort(numbers, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1 - o2; // This ensures ascending order
}
});
System.out.println("Sorted list (ascending): " + numbers);
}
}
Output:
Original list: [10, 5, 15, 3, 12] Sorted list (ascending): [3, 5, 10, 12, 15]
4. Step By Step Explanation
1. We initiate an ArrayList and populate it with some integer values.
2. We use the Comparator interface and create an anonymous inner class that implements the compare method. This method provides the criteria for sorting the objects in the list.
3. In the compare method, by returning the result of o1 subtracted from o2, we ensure that the numbers get sorted in ascending order. If o1 is less than o2, a negative value will be returned, positioning o1 before o2 in the sorted list.
4. The Collections.sort() method sorts our list based on the order specified by our Comparator.
5. Finally, both the original and the sorted lists are printed to observe the outcome.
Through the Comparator interface, Java provides a flexible way to specify custom orderings for collections, ensuring we can sort our data precisely the way we need.