1. Introduction
With the introduction of Java 8, lambdas brought a more concise and expressive way to implement interfaces with a single abstract method, such as the Comparator interface. In this tutorial, we’ll explore how to sort a list of integers in descending order using the Comparator interface combined with lambda expressions.
2. Program Steps
1. Initialize a list of integers.
2. Use a lambda expression to define a Comparator that will arrange the integers in descending order.
3. Utilize the Collections.sort() method to sort the list with the lambda-based Comparator.
4. Print the sorted list to the console.
3. Code Program
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class DescendingOrderLambdaComparator {
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 lambda-based comparator in descending order
Collections.sort(numbers, (o1, o2) -> o2 - o1);
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. Next, we use a lambda expression to provide an implementation for the Comparator interface. The lambda expression (o1, o2) -> o2 – o1 is an efficient and concise way to define our descending order sorting criterion.
3. In this lambda expression, by returning the result of o2 subtracted from o1, we ensure that the numbers get sorted in descending order. If o2 is larger than o1, a positive value will be returned, which means o2 will be placed before o1 in the sorted list.
4. The Collections.sort() method is then used to sort our list based on the order specified by our lambda-based Comparator.
5. Lastly, both the original and the sorted lists are printed to observe the sorting effect.
Thanks to lambda expressions, we can implement Comparator in a more concise manner, making our code cleaner and more readable.