Sort a String in Java (2 different ways) - GeeksforGeeks

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
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
Without using the sort() methodWith using sort() method
Without using the sort() method
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:
Convert string to array with the help of the toCharArray() method of String classNow use nested loops to check for swapping elements of an array.Print these character array elements.
Convert string to array with the help of the toCharArray() method of String class
Now use nested loops to check for swapping elements of an array.
Print these character array elements.
Example
Java
// Java program to Sort a String Alphabetically// Using toCharArray() method// Without using sort() method // Importing required classesimport java.io.*;import java.util.Arrays; // Main classclass 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:
The main logic is to toCharArray() method of String class over the input string to create a character array for the input string.Now use Arrays.sort(char c[]) method to sort character array.Use String class constructor to create a sorted string from char array.
The main logic is to toCharArray() method of String class over the input string to create a character array for the input string.
Now use Arrays.sort(char c[]) method to sort character array.
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 packageimport java.util.Arrays; // Main classpublic 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);    }}
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: 
Convert input string to Character array. There is no direct method to do it. We will use for loop to fill the array.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.Now we can use StringBuilder to convert the Character array to String.
Convert input string to Character array. There is no direct method to do it. We will use for loop to fill the array.
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.
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 classesimport java.util.Arrays;import java.util.Comparator; // Main classclass 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);    }}
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.
wurocpengpeng
ruhelaa48
simmytarika5
Java-String-Programs
Java-Strings
Java
Java-Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
HashMap in Java with Examples
Interfaces in Java
Object Oriented Programming (OOPs) Concept in Java
ArrayList in Java
How to iterate any Map in Java
Initialize an ArrayList in Java
Overriding in Java
Collections in Java
Singleton Class in Java
Multithreading in Java