In this source code example, we will use Java 8 stream API to sort a List of string objects in descending order with an example.
Sort List of String objects in Descending order using Java 8 Stream APIs
This example demonstrates different ways to sort List of String objects in descending order using Java 8 Stream APIs:
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class StreamListSorting {
public static void main(String[] args) {
List < String > fruits = new ArrayList < String > ();
fruits.add("Banana");
fruits.add("Apple");
fruits.add("Mango");
fruits.add("Orange");
// descending order
List < String > sortedList3 = fruits.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
System.out.println(sortedList3);
List < String > sortedList4 = fruits.stream().sorted((o1, o2) - > o2.compareTo(o1)).collect(Collectors.toList());
System.out.println(sortedList4);
}
}
Output:
[Orange, Mango, Banana, Apple]
[Orange, Mango, Banana, Apple]
Comments
Post a Comment