Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Sort a String in Java (2 different ways)

  • Difficulty Level : Easy
  • Last Updated : 14 Sep, 2021

String class doesn’t have any method that directly sorts a string, but we can sort a string by applying other methods one after other. String is a sequence of characters. In java, objects of String are immutable which means a constant and cannot be changed once created.

Creating a String

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

There are two ways to create a string in Java:

  • String literal
String s = “GeeksforGeeks”;
  • Using new keyword
String s = new String (“GeeksforGeeks”);

Note: As we know that String is immutable in java, hence in third step we have to create a new string.



Methods:

There exist two methods with which we can sort any string in java alphabetically

  1. Without using the sort() method
  2. With using sort() method

Illustration:

Input string : "geeksforgeeks"
Output string : "eeeefggkkorss"

Now let us discuss methods and implement the same. 

Method 1: Without using the sort() method

Here we will be laying an approach t sort a string without using any predefined logic. So, it also does becomes an important approach from an interview perceptive view.

Procedure:

  1. Convert string to array with the help of the toCharArray() method of String class
  2. Now use nested loops to check for swapping elements of an array.
  3. Print these character array elements.

Example



Java




// Java program to Sort a String Alphabetically
// Using toCharArray() method
// Without using sort() method
 
// Importing required classes
import java.io.*;
import java.util.Arrays;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args) throws Exception
    {
        // Custom string input
        String str = "geeksforgeeks";
       
        // Converting string into an array for computation
        char arr[] = str.toCharArray();
 
        // Nested loops for comparison of characters
        // in above character array
       
        char temp;
 
        int i = 0;
        while (i <= arr.length) {
            int j = i + 1;
            while (j <= arr.length) {
                if (arr[j] < arr[i]) {
                   
                    // Comparing the characters one by one
                    temp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = temp;
                }
                j += 1;
            }
            i += 1;
        }
 
        // By now loop is done means we have
        // iterated the whole array
        System.out.println(arr);
    }
}

Output:

eeeefggkkorss

Method 2: With using sort() method

2A With using sort() method- natural sorting

Procedure:

  1. The main logic is to toCharArray() method of String class over the input string to create a character array for the input string.
  2. Now use Arrays.sort(char c[]) method to sort character array.
  3. Use String class constructor to create a sorted string from char array.

Example 1

Java




// Java program to Sort a String Alphabetically
// Using toCharArray() method
// With using the sort() method
 
// Importing Arrays class from java.util package
import java.util.Arrays;
 
// Main class
public class GFG {
    // Method 1
    // To sort a string alphabetically
    public static String sortString(String inputString)
    {
        // Converting input string to character array
        char tempArray[] = inputString.toCharArray();
 
        // Sorting temp array using
        Arrays.sort(tempArray);
 
        // Returning new sorted string
        return new String(tempArray);
    }
 
    // Method 2
    // Main driver method
    public static void main(String[] args)
    {
        // Custom string as input
        String inputString = "geeksforgeeks";
        String outputString = sortString(inputString);
 
        // Print and display commands
 
        // Input string
        System.out.println("Input String : " + inputString);
        // Output string
        System.out.println("Output String : "
                           + outputString);
    }
}
Output
Input String : geeksforgeeks
Output String : eeeefggkkorss

2B With using sort() method- Custom sorting

Arrays.sort(char c[]) method sort characters based on their ASCII value, we can define our custom Comparator to sort a string. 

Illustration:

Input String : GeeksforGeeks
Output String : eeeefGGkkorss

Procedure: 

  1. Convert input string to Character array. There is no direct method to do it. We will use for loop to fill the array.
  2. Use Arrays.sort(T [ ], Comparator c) method to sort Character array. For this, we must have to implement compare() method based on our custom sorting behavior.
  3. Now we can use StringBuilder to convert the Character array to String.

Example 2

Java




// Java Program to Sort a Mixed String Containing
// Uppercase and Lowercase Characters
 
// Importing required classes
import java.util.Arrays;
import java.util.Comparator;
 
// Main class
class GFG {
    // Method 1
    // To sort a mixed string
    public static String sortString(String inputString)
    {
        // Converting input string to Character array
        Character tempArray[]
            = new Character[inputString.length()];
 
        for (int i = 0; i < inputString.length(); i++) {
            tempArray[i] = inputString.charAt(i);
        }
 
        // Sort, ignoring case during sorting
        Arrays.sort(tempArray, new Comparator<Character>() {
             
          // Method 2
            // To compare characters
            @Override
            public int compare(Character c1, Character c2)
            {
                // Ignoring case
                return Character.compare(
                    Character.toLowerCase(c1),
                    Character.toLowerCase(c2));
            }
        });
 
        // Using StringBuilder to convert Character array to
        // String
        StringBuilder sb
            = new StringBuilder(tempArray.length);
 
        for (Character c : tempArray)
            sb.append(c.charValue());
 
        return sb.toString();
    }
 
    // Method 3
    // MAin driver method
    public static void main(String[] args)
    {
        // Custom input string
        String inputString = "GeeksforGeeks";
 
        // Calling method 1 to sort input string
        // and storing in a string
        String outputString = sortString(inputString);
 
        // Print and display the input and output strings
        System.out.println("Input String : " + inputString);
        System.out.println("Output String : "
                           + outputString);
    }
}
Output
Input String : GeeksforGeeks
Output String : eeeefGGkkorss

Note:

public int compare(Object o1, Object o2) {} 
  • have to return -ve if o1 has to come before o2
  • have to return +ve if o1 has to come after o2
  • have to return 0 if o1 is equal to o2

This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!