Sorting Strings in Java using Arrays.sort()

JavaJavaBeginner
Practice Now

Introduction

In Java, there is no single method inside the String class for sorting purposes. However, we can utilize the fact that an array of characters can be easily sorted using various algorithms. There are multiple ways to sort strings in Java, such as using Arrays.sort(), Comparator in Arrays.sort(), or commonly used sorting algorithms like Selection Sort and Bubble Sort. In this lab, we will explore how to sort a string in Java using the Arrays.sort() method.

Write the code

In this step, we will write the Java program to sort a string using the Arrays.sort() function. The code takes an input string, converts it to a character array, sorts the array using the Arrays.sort() function and then converts it back to a string.

import java.util.Arrays;

public class SortString {
    public static void main(String[] args) {
        String originalString = "The quick brown fox jumps over the lazy dog";
        String sortedString = "";
        char[] tempArr = originalString.toCharArray();   // convert string to character array
        Arrays.sort(tempArr);   // sort character array
        sortedString = new String(tempArr);   // convert sorted character array to a string
        System.out.println("Original String: " + originalString);
        System.out.println("Sorted String: " + sortedString);
    }
}

Compile and run the code

Open the terminal and navigate to the ~/project directory. Compile the Java program using the following command:

javac SortString.java

Run the Java program using the following command:

java SortString

The output of the program will be:

Original String: The quick brown fox jumps over the lazy dog
Sorted String:    Tabcdeeefghhijklmnoooopqrrstuuvwxyz

Implement case insensitive sorting

In Java, the Arrays.sort() method compares characters using their Unicode values. To sort a string without regards to case-sensitivity, we can modify the sorting algorithm using a Comparator. In this step, we will edit our previous Java code to sort the string without regards to the case.

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

public class SortString {
    public static void main(String[] args) {
        String originalString = "The quick brown fox jumps over the lazy dog";
        String sortedString = "";
        Character[] tempArr = toCharacterArray(originalString.toLowerCase());   // convert lowercase string to Character array
        Arrays.sort(tempArr, new Comparator<Character>() {   // sort with case-insensitive comparator
            @Override
            public int compare(Character c1, Character c2) {
                return c1.compareTo(c2);
            }
        });
        StringBuilder sb = new StringBuilder(tempArr.length);   // create a StringBuilder object
        for (Character c : tempArr) {
            sb.append(c.charValue());   // add sorted characters to the StringBuilder object
        }
        sortedString = sb.toString();   // convert StringBuilder object to a string
        System.out.println("Original String: " + originalString);
        System.out.println("Sorted String: " + sortedString);
    }

    // method to convert a string to Character array
    private static Character[] toCharacterArray(String str) {
        Character[] arr = new Character[str.length()];
        for (int i = 0; i < str.length(); i++) {
            arr[i] = str.charAt(i);
        }
        return arr;
    }
}

Compile and run the updated code

Compile the updated Java program using the following command:

javac SortString.java

Run the Java program using the following command:

java SortString

The output of the program will be:

Original String: The quick brown fox jumps over the lazy dog
Sorted String:    abcdeeefghhijklmnoooopqrrsttuuvwxyz

Implement sorting using the traditional method

In this step, we will implement sorting on a character array using a traditional nested loop method. The algorithm will compare each character with the characters on its right and will swap the characters if the right character is smaller than the current character.

import java.util.Arrays;

public class SortString {
    public static void main(String[] args) {
        String originalString = "The quick brown fox jumps over the lazy dog";
        String sortedString = "";
        char[] tempArr = originalString.toCharArray();   // convert string to character array
        int n = tempArr.length;
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                if (tempArr[i] > tempArr[j]) {
                    char temp = tempArr[i];
                    tempArr[i] = tempArr[j];
                    tempArr[j] = temp;
                }
            }
        }
        sortedString = new String(tempArr);   // convert sorted character array to a string
        System.out.println("Original String: " + originalString);
        System.out.println("Sorted String: " + sortedString);
    }
}

Compile and run the updated code

Compile the updated Java program using the previous command:

javac SortString.java

Run the Java program using the following command:

java SortString

The output of the program will be:

Original String: The quick brown fox jumps over the lazy dog
Sorted String:    Tabcdeeefghhijklmnoooopqrrstuuvwxyz

Summary

In this lab, we learned how to sort a string in Java using Arrays.sort() method. We also learned how to implement case-insensitive sorting using Comparator and traditional sorting using nested loops.

Other Java Tutorials you may like