Sort a String in Java
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import java.util.Arrays; class Main { public static void main(String[] args) { String str = "CADB"; char[] chars = str.toCharArray(); Arrays.sort(chars); str = new String(chars); System.out.println(str); } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
class Main { public static void main(String[] args) { String str = "CADB"; str = str.chars() // IntStream .sorted() .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append) .toString(); System.out.println(str); } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import java.util.stream.Collectors; import java.util.stream.Stream; class Main { public static void main(String[] args) { String str = "CADB"; str = Stream.of(str.split("")) .sorted() .collect(Collectors.joining()); System.out.println(str); } } |
That’s all about sorting a Java String.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)