Learn to arrange an array of strings alphabetically using Stream.sorted() and Arrays.sort() methods. Also, learn to reverse sort using Comparator.reverseOrder().
1. Stream.sorted() – Java 8
Java 8 stream APIs have introduced a lot of exciting features to write code in very precise ways which are more readable.
This example sorts the string array in a single line code using Stream. It uses the Stream.sorted() method which helps in sorting a stream of objects in their natural order or according to the provided Comparator.
For reverse sorting the array, use Comparator.reverseOrder().
// Unsorted string array
String[] strArray = { "Alex", "Charles", "Dean", "Amanda", "Brian" };
// Sorting the strings
strArray = Stream.of(strArray)
.sorted()
.toArray(String[]::new);
// Sorted array
System.out.println("Sorted : " + Arrays.toString(strArray));
// Reverse sorting example
strArray = Stream.of(strArray)
.sorted(Comparator.reverseOrder())
.toArray(String[]::new);
// Reverse Sorted array
System.out.println("Sorted : " + Arrays.toString(strArray));
Program output.
Sorted : [Alex, Amanda, Brian, Charles, Dean] Reverse Sorted : [Dean, Charles, Brian, Amanda, Alex]
2. Arrays.sort() – Java 7
Arrays.sort() provides similar functionality as Stream.sorted() if you are still in Java 7.
// Unsorted string array
String[] strArray = { "Alex", "Charles", "Dean", "Amanda", "Brian" };
// Sorting the strings
Arrays.sort(strArray);
// Sorted array
System.out.println("Sorted : " + Arrays.toString(strArray));
Arrays.sort(strArray, Comparator.reverseOrder());
// Reverse Sorted array
System.out.println("Sorted : " + Arrays.toString(strArray));
Program output.
Sorted : [Alex, Amanda, Brian, Charles, Dean] Reverse Sorted : [Dean, Charles, Brian, Amanda, Alex]
Drop me your questions related to comparing and sorting a string array in alphabetical order.
Happy Learning !!
Comments