4 ways in Java to sort a String alphabetically

Introduction:

This blog will show you how to sort a String alphabetically in Java. For example, the String ‘albert’ will become ‘abelrt’ after sorting. Since String is immutable, it will create a new String with the sorted characters. We will learn four different ways with examples in this post.

Method 1: By using two loops:

This is the simplest way to sort a String. We will use two for loops and one loop will run inside another loop. The outer loop will iterate over the characters one by one and for each character, the inner loop will compare it with all other characters to the right of that character. If any alphabetically small character is found by the inner loop, it will swap it with the character pointed by the outer loop.

The following program shows how to write this in Java:

import java.util.Scanner;

class FirstExample {
    public static void main(String[] args) {
        try (Scanner scanner = new Scanner(System.in)) {
            System.out.println("Enter a string:");
            String userInput = scanner.nextLine();

            char[] charArray = userInput.toCharArray();

            for (int i = 0; i < charArray.length; i++) {
                for (int j = i + 1; j < charArray.length; j++) {
                    if (Character.toLowerCase(charArray[j]) < Character.toLowerCase(charArray[i])) {
                        swapChars(i, j, charArray);
                    }
                }
            }

            System.out.println("Sorted string " + String.valueOf(charArray));
        }
    }

    private static void swapChars(int i, int j, char[] charArray) {
        char temp = charArray[i];
        charArray[i] = charArray[j];
        charArray[j] = temp;
    }

}

Download it on GitHub

Explanation:

The commented numbers in the above program denote the step numbers below:

  1. Create one Scanner object to read the user input String.

  2. Ask the user to enter a String. Read it and assign it to the userInput variable.

  3. We need to compare each character of this String, swap, and arrange them in ascending order. Since a String is immutable, we need to convert the String to an Array. It is using the toCharArray() method to convert it to an array of characters. It assigns the value to the charArray variable.

  4. It uses two nested for loops to sort the characters of the array. It converts the characters to lowercase before comparing.

  5. The swapChars method is used to swap two characters in an array. It takes the position of the characters in an array and the array as its parameters. If the character at index j is smaller than the character at index i, it swaps the characters of these positions.

  6. Finally, print out the sorted string to the user. It uses the String.valueOf method to convert the character array to String.

Sample Output :

If you run the above program, it will print outputs as below:

Enter a string :
Alphabet
Sorted string Aabehlpt

Enter a string :
elephant
Sorted string aeehlnpt

Method 2: Sort a String by converting it to an Array:

The previous method converts the String to an array of characters and used two for loops to sort the characters. We can also use the Arrays.sort method to sort the content of the character array. The sorted array can be converted back to a String.

The following program shows how it works:

import java.util.Arrays;
import java.util.Scanner;

class SecondExample {
    public static void main(String[] args) {
        try (Scanner scanner = new Scanner(System.in)) {
            System.out.println("Enter a string:");
            String userInput = scanner.nextLine();

            char[] charArray = userInput.toCharArray();

            Arrays.sort(charArray);
            System.out.println("Sorted string: " + String.valueOf(charArray));
        }
    }
}

Download it on GitHub

The only problem with this method is that it will fail to sort a string with both uppercase and lowercase letters. If the String has only uppercase or lowercase letters, it will work.

Example:

Enter a string:
Elephant
Sorted string: Eaehlnpt

Enter a string:
elephant
Sorted string: aeehlnpt

Enter a string:
ELEPHANT
Sorted string: AEEHLNPT

As you can see here, the first example failed as the ASCII value of E is 69 and the ASCII value of a is 97. So, it placed E before a.

Java sort string example

Method 3: How to sort a String by using a comparator:

We can use a Comparator with the Arrays.sort() method. We need to convert the string to a Character array. The following program shows how to sort a given String with a comparator:

import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;

class ThirdExample {
    public static void main(String[] args) {
        try (Scanner scanner = new Scanner(System.in)) {
            System.out.println("Enter a string:");
            String userInput = scanner.nextLine();

            Character[] charArray = new Character[userInput.length()];

            for (int i = 0; i < userInput.length(); i++) {
                charArray[i] = userInput.charAt(i);
            }

            Arrays.sort(charArray, Comparator.comparingInt(Character::toLowerCase));

            StringBuilder sb = new StringBuilder(charArray.length);
            for (Character c : charArray)
                sb.append(c.charValue());

            System.out.println("Sorted string: " + sb.toString());
        }
    }
}

Download it on GitHub

  1. It creates one Character array from the string. It is assigned to the charArray variable.
  2. It passes one lambda function to the sort method.
Arrays.sort(charArray, new Comparator() {
    @Override
    public int compare(Character o1, Character o2) {
        return Character.compare(Character.toLowerCase(o1),
                Character.toLowerCase(o2));
    }
});

Finally, it converts the character array to a StringBuilder object and it is converted back to String by using the toString() method.

Example:

The above program will print output as below:

Enter a string:
Elephant
Sorted string: aEehlnpt

Method 4: Sort a String by using Stream:

Another way is to use the Stream API to sort the characters. We can convert the String to a Stream, sort the characters and convert it back to a String. The following program shows how it works:

import java.util.Comparator;
import java.util.Scanner;
import java.util.stream.Collectors;
import java.util.stream.Stream;

class FourthExample {
    public static void main(String[] args) {
        try (Scanner scanner = new Scanner(System.in)) {
            System.out.println("Enter a string:");
            String userInput = scanner.nextLine();

            String finalString = Stream.of(userInput.split(""))
                    .sorted(Comparator.comparingInt(o -> Character.toLowerCase(o.charAt(0))))
                    .collect(Collectors.joining());

            System.out.println("Sorted string: " + finalString);
        }
    }
}

Download it on GitHub

We are using the same comparator function in the sorted() method. If you run the program, it will print output as below:

Enter a string:
Elephant
Sorted string: aEehlnpt

java sort string character alphabetically

Conclusion:

We have learned four different ways to sort the characters in a string in Java. You can raise a PR on GitHub if you want to add anything else.

Similar tutorials: