Java Program: Sort List of Strings in Ascending and Descending Order using Streams
Java Stream: Exercise-6 with Solution
Write a Java program to sort a list of strings in alphabetical order, ascending and descending using streams.
Sample Solution:
Java Code:
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List < String > colors = Arrays.asList("Red", "Green", "Blue", "Pink", "Brown");
System.out.println("Original List of strings(colors): " + colors);
// Sort strings in ascending order
List < String > ascendingOrder = colors.stream()
.sorted()
.collect(Collectors.toList());
// Sort strings in descending order
List < String > descendingOrder = colors.stream()
.sorted(Comparator.reverseOrder())
.collect(Collectors.toList());
System.out.println("\nSorted in Ascending Order: " + ascendingOrder);
System.out.println("\nSorted in Descending Order: " + descendingOrder);
}
}
Sample Output:
Original List of strings(colors): [Red, Green, Blue, Pink, Brown] Sorted in Ascending Order: [Blue, Brown, Green, Pink, Red] Sorted in Descending Order: [Red, Pink, Green, Brown, Blue]
Explanation:
In the above exercise,
Using streams, we call the sorted() method without passing any comparator to sort the strings in ascending order based on their natural order (lexicographically). We collect the sorted strings into a new list using the toList() method.
To sort the strings in descending order, we pass Comparator.reverseOrder() as the comparator to the sorted() method. This reverses the natural order and sorts the strings in descending order.
Flowchart:
Java Code Editor:
Improve this sample solution and post your code through Disqus
Previous: Count Strings Starting with Specific Letter using Streams.
Next: Find Maximum and Minimum Values in a List of Integers using Streams.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/java-exercises/stream/java-stream-exercise-6.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics