×

How to sort a String in Java

Sorting is the process of putting the elements in a certain order, either ascending or descending. Mostly the alphabetical order or natural order is used for a string. In other words, sorting is the process of converting data in standard form (to make it human-readable).

Java String

In Java, a string is considered as an object which stores the sequence of character values. A character array works similar to a Java string.

Java strings are immutable in nature, i.e., we cannot modify the value of string object once it is created. Therefore, when we sort a string, the characters are shuffled after sorting, and we have to create a new string to store the sorted String.

In Java, the String class does not have any method to sort a string directly; however, there are different methods and classes to sort a string.

Sorting a String in Java

Following are the ways sort a string in Java:

  1. Using Arrays.sort() method
  2. Using String.chars() method (Java 8)
  3. Manual sort with toCharArray() method
  4. Using Comparator class

Using Arrays.sort() method

The sort() method of the Arrays class sorts the characters on the basis of ASCII value, where we can define the custom Comparator to sort a string.

The steps to use Arrays.sort() method are:

  1. Convert the input string into a character array using the toCharArray() method.
  2. Once we get the character array, sort it using the Arrays.sort() method.
  3. Again, convert the sorted character array back to String. Here, we pass this array to the constructor of the String class.

Example:

Let's consider the below example where we sort the specified String in Java.

SortMethod.java

//importing Arrays class
import java.util.Arrays;
 
public class SortMethod
{
    public static void main(String[] args)
    {
        //declaring and initializing a string
        String str = "javatpoint";
        
        //converting the string into character array using toCharArray() method
        char[] ch = str.toCharArray();


        //using sort() method to sort the array
        Arrays.sort(ch);


        //converting the sorted array back to String
        //storing it in new string
        String strNew = new String(ch);
 
        //printing the before sorting
        System.out.println("Input string: " + str);
        //printing the after sorting
        System.out.println("Output string: " + strNew);
    }
} 

Output:

How to sort a String in Java

Using String.chars() method (Java 8)

Java 8 Stream class provides the feature of sorting a string. It has a String.chars() method, which returns IntStream, which depicts the integer representation of the character of String. Once we get the IntStream, we can sort it and store the integers in sorted order in a StringBuilder object.

Example 1:

Consider the following example to sort the String using the String.chars() method in Java.

CharsMethod.java

public class CharsMethod
{
    public static void main(String[ ] args)
    {
        //declaring and initializing a string
        String str = "javatpoint";
        
        //converting the string into IntStream using chars()
        String strNew = str.chars()
                .sorted()
                .collect(
                        StringBuilder :: new,
                        StringBuilder :: appendCodePoint,
                        StringBuilder :: append)
                .toString();
    
 
        //printing the before sorting
        System.out.println("Input string: " + str);
        //printing the after sorting
        System.out.println("Output string: " + strNew);
    }
}

Output:

How to sort a String in Java

Example 2:

Rather than creating IntStream, we can convert each character in the String to a single character string and get a stream of strings.

Here, we need to import the stream.Collectors class and stream.Stream class of java.util package.

Let's consider the below example to understand.

StringSortUsingCollectors.java

//importing necessary classes
import java.util.stream.Collectors;
import java.util.stream.Stream;


public class StringSortUsingCollectors
{
    public static void main(String[ ] args)
    {
        //declaring and initializing a string
        String str = "helloworld";
        
        //converting the string into IntStream using chars()
        String strNew = Stream.of (str.split(""))
                    .sorted()
                    .collect(Collectors.joining());
    
 
        //printing the before sorting
        System.out.println("Input string: " + str);
        //printing the after sorting
        System.out.println("Output string: " + strNew);
    }
}

Output:

How to sort a String in Java

Manual sort using for() loop

We can also sort a Java string manually using the for loop and compare the string elements to shuffle and place them into ascending or descending order.

Here, we use two for loops to compare each element with another.

Following are the steps to sort a string manually in Java

  1. Convert the input string into a character array using the toCharArray() method.
  2. Sort the array using any array sorting technique. Here we are using bubble sort.
    • Compare the first two elements of an array.
    • If the first element is greater than the second, swap (switch their positions).
    • Similarly, compare the second and third element and swap if the second element is greater than the third.
    • Repeat the process until the end of the array.

Example:

Let’s consider the following example where we are sorting the string using manual sorting method.

ManualSortOfString.java

//importing necessary classes
import java.util.Arrays;
import java.util.Scanner;
public class ManualSortOfString {
   public static void main(String args[ ]) {
    
      int temp, size;
      Scanner sc = new Scanner(System.in);


      //accepting String from the user
      System.out.println("Enter a string value: ");
      String str = sc.nextLine();


      //converting the string into character array
      char charArray[] = str.toCharArray();


      //finding the length of above array
      size = charArray.length;


      //traversing through the array to sort the elements
      for(int i = 0; i < size; i++ ){
         for(int j = i + 1; j < size; j++){
            if (charArray[i] > charArray[j]){
               temp = charArray[i];
               charArray[i] = charArray[j];
               charArray[j] = (char) temp;
            }
         }
      }


      //converting the character array back to string
      String strNew = new String(charArray);


      //printing the before sorting
      System.out.println("Input string: " + str);
      //printing the after sorting
      System.out.println("Output string: " + strNew);
 
 }
}

Output 1:

How to sort a String in Java

Output 2:

How to sort a String in Java

As we can see, the first output of the above example sorts all the lower case characters. However, the second output does not sort the String character in the upper case as it is a mixed string.

Sorting a mixed string (having uppercase and lowercase characters)

In order to sort a mixed string, i.e., a string with both uppercase and lower case characters, we can use the Comparator class of Java.

Following are the steps to sort a mixed string:

  1. Convert input string into a character array. Here we will use the for loop to add elements to the array.
  2. We will sort the character array using the Arrays.sort( T [ ], Comparator c) method. To use this, we have to implement the compare() method based on the custom sorting behavior.
  3. Now we will use the StringBuilder class to convert the sorted character array back to the String.

Example:

Let's consider the below example to understand how to sort a mixed string in Java using for loop.

MixedStringSort.java

//importing necessary classes
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
  
public class MixedStringSort {
public static void main(String[] args) {


Scanner sc = new Scanner(System.in);


//accepting string from the user
System.out.println("Enter a string value: ");
String str = sc.nextLine();

//finding the length of input string
int len = str.length();


//converting the string into character array
Character charArray[] = new Character[len];


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


//sorting the string
//ignoring case during sorting
Arrays.sort(charArray, new Comparator<Character>(){
@Override
public int compare(Character char1, Character char2)
            {
                // ignoring case
                return Character.compare(Character.toLowerCase(char1),
                                        Character.toLowerCase(char2));
            } 
});


//convert character array to String using StringBuilder class
StringBuilder sb_obj = new StringBuilder(charArray.length);


for (Character c : charArray){
sb_obj.append( c.charArray() );
}


return sb_obj.toString();


}


}

Output:

How to sort a String in Java

In the above output, all the characters of the string 'JavaTpoint' are sorted irrespective of the case.

In this way, we have learned how to sort a string in Java using different methods and classes.


Related Topics

Java Math cbrt() Method

The cbrt() method of Math class returns the cube root of a double value. Syntax: public static double cbrt(double a) Parameters: The parameter ‘a’ represents the value whose cube root is to be determined. Return...

2 minutes read.

Char and String differences in Java

Characters in Java Character (char) belongs to the characters group, which represents symbols in a character set, such as alphabets and numerals. A Java char has 16 bits in length and has a range...

5 minutes read.

Java Thread Dump Analyzer

Thread: A thread is a PC program that is stacked into the PC's memory and is under execution. It tends to be executed by a processor or a bunch of processors....

15 minutes read.

Static Array in Java

In this tutorial, we will study static arrays in Java. An array is a data structure that is of great importance in any programming language. It is classified into two...

3 minutes read.

Java List Node

In Java, List Node is the same as the single linked list, which is the collection of nodes. So, we can say, the list nodes are grouped together to get...

8 minutes read.

How to convert double to String in Java

How to Convert double to String in Java It is used when we want to convert double primitive to String type. There are two methods to convert double to String. Using String.valueOf()...

2 minutes read.

Hashtable in Java

Hashtable in Java The Hashtable class implements the Map interface and extends the Dictionary class. It implements a hash table which shows the key-value relation, i.e., it maps the keys to the values....

9 minutes read.

Java Thread class

Thread class The thread represents a part of the process. Every process can have multiple associated threads in which every thread may execute the same or different job. By default, each thread assigns...

16 minutes read.

Merge Sort in Java

Merge Sort in Java Merge sort in Java uses the divide and conquer approach to sort the given array/ list. There are three steps involved in the merge sort. 1) Divide the...

5 minutes read.

How to Convert String to char in Java

How to Convert String to char in Java There are two methods to convert String to char are: Using charAt() method Using tocharArray() method Using charAt() method This is the method of String class that...

3 minutes read.

Java Binary Operators

In this article, we are going to discuss about the binary operators in Java and their operations. Also, an example program will be discussed along with the operations. These are...

6 minutes read.

Fibonacci Series Program in Java

Fibonacci Series Program in Java using Recursion Fibonacci series is a series whose every term is comprised of adding its previous two terms, barring the first two terms 0 and 1....

3 minutes read.

Mutable class in Java

A language for object-oriented programming is Java. Because this is an object-oriented language of programming, all of its mechanisms and methods are based on objects. Java has a concept of...

6 minutes read.

Java Project Ideas

When it comes to constructing projects, Java is regarded as one of the best languages and is also one of the most paid. Java excels in any application, whether it...

10 minutes read.

Big Decimal class in Java

The fairly Big pretty Decimal class provides operations for arithmetic, rounding, comparison and format conversion in a sort of big way. It can handle generally large and very small floating-point...

6 minutes read.

Perfect Number Program in Java

Perfect Number Program in Java A perfect number is a number whose sum of all the factors, excluding the number itself, is equal to the number. For example, 28 is a...

4 minutes read.

What’s new in Java 12

On March 19th, 2019, the Java 12th edition was released. After releasing this edition, they have decided to release every new edition every six months. This version is the advanced...

5 minutes read.

Difference Between Java and PHP

The two most used programming languages are PHP and Java. Both of them have a lot of similarities and distinctions. Let's first grasp each of them individually before examining their...

3 minutes read.

Stack Program in Java

Stack Program in Java The Stack class is part of the collection framework that inherits the Vector class. Thus, the Stack class can also be called a subclass of the Vector...

5 minutes read.

How to Convert Date to Timestamp in Java

How to Convert Date to Timestamp in Java You can convert Date to Timestamp by using the getTime() method of Date class. It returns the long millisecond from Epoch which can...

1 minute read.