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: