Java Sort String Characters Alphabetically

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?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

3 thoughts on “Java Sort String Characters Alphabetically”

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.