Java example to sort characters of String in alphabetical order – using Stream.sorted()
and Arrays.sort()
methods.
1) Sort string with Stream API
Example of sorting the characters of string using Stream.sorted()
API.
String randomString = "adcbgekhs"; String sortedChars = Stream.of( randomString.split("") ) .sorted() .collect(Collectors.joining()); System.out.println(sortedChars); // abcdeghks
2) Arrays.sort()
Example of sort a string using Arrays.sort()
method.
String randomString = "adcbgekhs"; //Convert string to char array char[] chars = randomString.toCharArray(); //Sort char array Arrays.sort(chars); //Convert char array to string String sortedString = String.valueOf(chars); System.out.println(sortedChars); // abcdeghks
Drop me your questions in comments section.
Happy Learning !!
Reference:
Stream.sorted() Java Doc
Arrays.sort() Java Doc
Was this post helpful?
Let us know if you liked the post. That’s the only way we can improve.
Shreyas
How do I sort The characters in one string in ascending order of their ASCII values??
Alejandro
How about comparing 2 strings that have been already ordered?
Lokesh Gupta
Didn’t get the question.