1. Introduction
The Comparator interface is a powerful tool in Java to define custom orderings for collections of objects, especially when you do not have control over the original class definition. With the advent of lambda expressions in Java 8, creating Comparator instances has become much more concise and expressive. In this guide, we will explore how to use lambda expressions to create comparators for both ascending and descending orders on various types.
2. Program Steps
1. Define a list of integers and sort it in ascending order.
2. Sort the same list in descending order.
3. Define a list of strings and sort it in ascending order.
4. Sort the same list of strings in descending order.
3. Code Program
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class ComparatorWithLambda {
public static void main(String[] args) {
// 1. Define a list of integers and sort it in ascending order.
List<Integer> numbers = new ArrayList<>();
numbers.add(3);
numbers.add(1);
numbers.add(4);
numbers.add(2);
numbers.sort(Comparator.naturalOrder());
System.out.println("Numbers in ascending order: " + numbers);
// 2. Sort the same list in descending order.
numbers.sort(Comparator.reverseOrder());
System.out.println("Numbers in descending order: " + numbers);
// 3. Define a list of strings and sort it in ascending order.
List<String> words = new ArrayList<>();
words.add("Banana");
words.add("Apple");
words.add("Cherry");
words.sort((word1, word2) -> word1.compareTo(word2));
System.out.println("Words in ascending order: " + words);
// 4. Sort the same list of strings in descending order.
words.sort((word1, word2) -> word2.compareTo(word1));
System.out.println("Words in descending order: " + words);
}
}
Output:
Numbers in ascending order: [1, 2, 3, 4] Numbers in descending order: [4, 3, 2, 1] Words in ascending order: [Apple, Banana, Cherry] Words in descending order: [Cherry, Banana, Apple]
4. Step By Step Explanation
1. We first define a list of integers. For sorting it in ascending order, we use Comparator.naturalOrder(), which provides a comparator consistent with the natural ordering.
2. To sort the list of integers in descending order, we use Comparator.reverseOrder().
3. For a list of strings, we define our lambda expression for ascending order. The lambda expression is essentially a shorter form of an anonymous class. Here, (word1, word2) -> word1.compareTo(word2) is equivalent to a comparator that compares two words based on their natural order.
4. To sort the list of strings in descending order, we modify our lambda expression to compare in reverse.
Lambda expressions offer a concise way to represent Comparator instances without the need for anonymous classes. This makes the code more readable and clean.