Sort a String Alphabetically in Java

This Java tutorial discusses the different approaches to sort a string alphabetically. When sorting alphabetically, we essentially sort the characters of the string in alphabetical order.

1. Sort a String using Java 8 Streams

The Stream.sorted() method sorts the stream elements in the natural order. In case of strings, the natural order is the alphabetical order. So we need to perform the following pseudo steps:

  • Create a stream of characters from the String
  • Sort the stream
  • Join the Stream to get a new sorted string

The following Java program demonstrates sorting the characters of a string using Stream.sorted() API.

String string = "adcbgekhs";

String sortedString = Stream.of( string.split("") )

System.out.println(sortedString);	// abcdeghks

2. Sort a String using Arrays.sort()

The Arrays.sort() also does the same thing as Stream.sort() does. So the steps to sort a string remains the same in this solution also. This time, we create a new array of characters, sort the array and then join the array to produce the sorted string.

String string = "adcbgekhs";

//Convert string to char array
char[] chars = string.toCharArray();	

//Sort char array

//Convert char array to string
String sortedString = String.valueOf(chars);

System.out.println(sortedChars);	// abcdeghks

3. Without using sort() Method

If we do not want to use the inbuilt Java APIs, we can use the Java arrays to iterate over the characters of the String and sort them in a loop.

  • Convert string to an array of characters using toCharArray() method
  • Loop through the array elements and check for swapping elements of an array by comparing the code value
  • Print the array after the loop finishes
String string = "adcbgekhs";
String sortedString = sortWithArray(string);

//The custom sorting function using arrays

static String sortWithArray(String str) {

	char arr[] = str.toCharArray();
	char temp;

	int i = 0;
	while (i < arr.length) {
	  int j = i + 1;
	  while (j < arr.length) {
	    if (arr[j] < arr[i]) {
	      temp = arr[i];
	      arr[i] = arr[j];
	      arr[j] = temp;
	    j += 1;
	  i += 1;
	return String.copyValueOf(arr);

4. Conclusion

This Java tutorial discusses different ways to sort a string alphabetically with examples. We learned to use the Stream.sort(), Arrays.sort() and custom sort() method using simple arrays and swapping.

Drop me your questions in the comments section.

Happy Learning !!

Source Code on Github


Notify of
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode