This post will discuss how to sort a string in Java.

We know that string is immutable in Java. That means once a String object is created, it cannot be modified in memory. In other words, if we’re to shuffle the characters of a string in sorted order, we have to create a new string. There are various ways to achieve that, as shown below:

1. Using Arrays.sort() method

The idea is to convert the given string to a character array using the toCharArray() method, sort the array using the Arrays.sort() method and construct a new string from the character array using String constructor.

Download  Run Code

2. Using Java 8

We can also use Java 8 Stream for sorting a string. Java 8 provides a new method, String.chars(), which returns an IntStream (a stream of ints) representing an integer representation of characters in the String. After getting the IntStream, we sort it and collect each character in sorted order into a StringBuilder.

Download  Run Code

 
Instead of creating an IntStream, we can also convert each character in the string to a single-character String and get a stream of strings instead.

Download  Run Code

That’s all about sorting a Java String.