You can sort a list using a lambda expression with the sort() method from the Collections class or by using the List interface’s sort() method in Java 8. The lambda expression is passed as a comparator to define the sorting logic.

Example

Sorting in Ascending Order

To sort a list of integers in ascending order:

List<Integer> numbers = Arrays.asList(5, 3, 8, 1, 2);
numbers.sort((a, b) -> a - b);  // Lambda expression for ascending order
System.out.println(numbers);  // Output: [1, 2, 3, 5, 8]

Sorting in Descending Order

To sort the list in descending order:

List<Integer> numbers = Arrays.asList(5, 3, 8, 1, 2);
numbers.sort((a, b) -> b - a);  // Lambda expression for descending order
System.out.println(numbers);  // Output: [8, 5, 3, 2, 1]

Sorting a List of Strings

For a list of strings, you can sort them alphabetically:

List<String> words = Arrays.asList("Java", "Python", "C++");
words.sort((a, b) -> a.compareTo(b));  // Sorting in alphabetical order
System.out.println(words);  // Output: [C++, Java, Python]

Key Points

  • Lambda Expression: The lambda (a, b) -> a - b or (a, b) -> a.compareTo(b) defines the comparison logic.
  • sort() Method: The sort() method sorts the list in-place (modifying the original list).

In summary, you can use a lambda expression to define custom sorting logic when using the sort() method on a list, allowing for flexible and concise sorting of elements.