Java does not have a direct method to sort a string. You can do it by converting the string to char array and use methods of Arrays
class in java.util
package to sort
Sort a String in alphabetically / ascending order
- Convert a string
str
tochar
array by usingstr.toCharArray()
method - Sort the
char
array ascending by usingArrays.sort
method - Convert
char
array to the sorted string by usingString.valueOf
method
Output
abc
Sort a String in descending order by using Java 8+ Stream API
- Convert string
str
toCharacter[]
array by using Stream APIstr.chars()
- Sort the
Character[]
array descending by usingArrays.sort
method withComparator.reverseOrder
- Convert
Character[]
array to the sorted string by usingArrays.stream
method
Output
cba
Sort a String in descending order by using StringBuilder
- Sort a string in ascending order by using
Arrays.sort
method - Then using
reverse
method ofStringBuider
to get the string in descending order
Output
cba
Notes
- Arrays.stream, Comparator.reverseOrder, Collectors.joining, str.chars methods are defined in java.util package and available since Java 8