How to alphabetically sort a String in Java with just three lines of code
If you need to alphabetically sort a
String in Java, then you’ll want to read on and memorize this order of operations.
First of all, there is no native function in Java to just take a
String and then sort it.
- Turn the
Stringinto an array of characters (
- Sort the array of characters
- Create a new
Stringusing the array of characters
Examples of sorted Strings
- “dcba” → “abcd”
- “gggggc” → “cggggg”
- “za” → “az”
So to reiterate, first we are defining a character array and then initializing it with our input string,
str, that has the
toCharArray() function applied to it. The
toCharArray() function returns exactly an array of characters, so the type matches.
Then, we use the
Arrays.sort() method which is a class method of
Java.util.Arrays. This does the sorting work for us.
However, the sorted array is still in the form of an array of characters. In order to get back to a
String, we then create a new
String and then pass the array of characters into its class constructor (basically, we just provide it as the sole argument).
With this, we have an alphabetically sorted
String, and we can return it.
This can come in handy when you want to sort a
String, and while it’s not immediately obvious, it’s something you can memorize and quickly apply the next time you need it.