String Sorting is one of the most frequently used questions and unavoidable operations in java basics.
Also, String sorting is the most expected feature in any kind of functionalities in applications. Here you are going to learn the three simplest ways to sort any kind of stings in Java.
let us see one by one with examples
Method 1: Sorting the String Alphabhatically Using Arrays.sort()?
The below example is the way to convert a String sung Arrays.sort().
char[] sortString= "Text".toCharArray(); Arrays.sort(sortString); System.out.println("Sorting the String through Using Arrays.sort() : "+String.valueOf(sortString));
Output :
Sorting the String through Using Arrays.sort() : Tetx
In the above example, We have used Arrays.sort()from java.util package. sort() method takes char[] as input and sorts the elements in ascending.
Method 2: Sorting the String basis on Cases Using List.sort() with Comparator?
Example to sort String using the List.sort() with Comparator.
List<String> listData = new ArrayList<String>(); listData.add("x"); listData.add("a"); listData.add("z"); listData.sort(Comparator.naturalOrder()); System.out.println("Natural Order Sorting the String through List sort : "+listData); listData.sort(Comparator.reverseOrder()); System.out.println("Decending Sorting the String through List Sort : "+listData);
Output :
Natural Order Sorting the String through List sort : [a, x, z] Decending Sorting the String through List Sort : [z, x, a]
In the above example, we have used list.sort() and Comparators. naturalOrder() return the output of the data in ascending order, whereas reverseOrder() makes data print in reverse order.
Methods 3: Sort the String using Java Stream API ?
Java 8 provides plenty of basic options to play with a String, This makes the code reusable and developer-friendly in readability.
String stringData = "xyzabC"; String sortedString = Stream.of(stringData.split("")).sorted().collect(Collectors.joining()); System.out.println("Sorting the String through Stream.sorted() : "+sortedString);
Output :
Sorting the String through Stream.sorted() : Cabxyz
The above example to sort the String using Stream API, its simplest of all the was we learned. Here we have used sorted() function available under Stream Class and subsequently the result of the Sorted string collected as joining() function which will concatenate input element into a string.