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.
Java: Tips of the Day
Converts a string from camelcase:
public static String fromCamelCase(String input, String separator) { return input .replaceAll("([a-z\\d])([A-Z])", "$1" + separator + "$2") .toLowerCase(); }
Ref: https://bit.ly/3u09A9E
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook