Sort Characters in a String in Java
Problem
Sorting a string's characters means rearranging every character it contains into ascending order, based on each character's code.
Given a string, arrange its characters in alphabetical order.
Java Program
import java.util.Arrays;
public class SortCharacters {
public static void main(String[] args) {
String str = "banana";
char[] chars = str.toCharArray(); // copy the characters out into a mutable array
Arrays.sort(chars); // sorts the array in place, ascending by character code
System.out.println(new String(chars)); // rebuilds a String from the sorted array
}
}Output
Core Logic
Converting the string into a character array, sorting that array in place, and rebuilding a string from it reorders every character.
- 1
str.toCharArray()converts the string into achar[]holding every character. - 2
Arrays.sort(chars)sorts that array in place, in ascending order by character code. - 3
new String(chars)builds a brand-newStringfrom the now-sorted array.
"banana", the array ['b','a','n','a','n','a'] sorts to ['a','a','a','b','n','n'], producing "aaabnn".Key Point: Arrays.sort() works directly on the char[], not the original String — strings are immutable in Java, so the characters have to be copied out into a mutable array first.
Why: toCharArray() copies every character into a new array, and Arrays.sort() then runs an O(n log n) comparison sort over it.
Key Concepts
Approach 2: Java 8
import java.util.stream.Collectors;
public class SortCharactersStream {
public static void main(String[] args) {
String str = "banana";
// sorted() sorts the character codes; the rest reassembles them into a String
String result = str.chars()
.sorted()
.mapToObj(c -> String.valueOf((char) c))
.collect(Collectors.joining());
System.out.println(result);
}
}
Output
Core Logic
The same sort can be expressed as a stream pipeline — sort the character codes directly, then join them back into a string.
- 1
str.chars()returns anIntStreamof the string's character codes. - 2
.sorted()puts those codes into ascending order, the stream equivalent ofArrays.sort()on achar[]. - 3
.mapToObj(c -> String.valueOf((char) c))converts each sorted code back into a one-characterString. - 4
.collect(Collectors.joining())concatenates them all back into the final sorted string.
"banana"'s character codes and joining them produces the same result as the array version: "aaabnn".Key Point: This does the same O(n log n) sort as the array version, just without ever touching a char[] directly.
Why: sorted() still performs the same comparison sort over every character, and Collectors.joining() builds a result string holding all n characters.