×

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

Interface Program in Java

Interface Program in Java In the previous topic, we discussed that abstraction is possible through the interface and abstract class. An abstract class provides partial to 100% abstraction. 100 %abstraction in...

4 minutes read.

How to run Java Program in Eclipse

How to run Java Program in Eclipse In this section, we will learn how to write, save, compile, and execute or run a Java program in Eclipse. Eclipse is one of...

2 minutes read.

Java Switch Keyword

In this article we are going to learn the concept of a java switch keyword. Generally, java case keyword is used with the switch statements or keyword.Switch keyword is implemented in...

3 minutes read.

How to create an array in Java

An array is a linear data structure stores a collection of fixed number ofelements of similar type. The size of an array is specified when it is created. The array...

14 minutes read.

Java Macros

Macros are additions to the JDK 7 compiler in Java. Compile time macros are added and supported. Macros are Java classes that are instantiated and executed during the compilation process....

2 minutes read.

Comparator vs Comparable in Java

Comparator Vs Comparable in Java In Java, sorting of primitive data types can be done using different inbuilt functions that are available. But for sorting the collection of objects or types...

4 minutes read.

Zebra Puzzle Problem in Java

Complex puzzles like the zebra puzzle demand a lot of work and mental training to complete. Because it was created by renowned German scientist Albert Einstein, it is also sometimes...

10 minutes read.

How to stop execution after a certain time in Java

We will learn how to stop a long-running execution after a set amount of time in this post. We will take a look at a few alternative approaches to this...

6 minutes read.

List of Constants in Java

In this tutorial, we are going to deal with constants available in Java.Every programming language has its constants. Similarly, Javaalso has got constants of its own. In this tutorial, we will...

6 minutes read.

Java Enum Keyword

Definition: A data type in Java called Enum has a respect to supply of constants. The weekdays (SUN, MON, TUE, WED, THU, FRI, and SAT), directions (NORTH, SOUTH, EAST, and WEST),...

4 minutes read.

Java String lastIndexOf() method

Java String lastIndexOf() method returns last index of character or substring in a String. Syntax: Method Description int lastIndexOf(int ch)It returns last index position for the given char valueint lastIndexOf(int ch, int...

2 minutes read.

What is string in Java why it's immutable

String in Java Strings are a series of characters commonly used in Java language, which are considered objects in the Java. To create and manipulate strings, java will provide the String...

4 minutes read.

Null Pointer Exception in Java

It is a runtime error exception. The null value is allocated to the object reference in this exception. We will explicitly throw this null pointer exception when the program wants...

3 minutes read.

Figurate Number in Java

There have been several uses for figurate or figural numerals throughout history. A number that may be expressed by regular, distinct geometric shapes with spaced evenly points is referred to...

4 minutes read.

Java Long Keyword

Long is a primitive data type in Java. To initilize variables, we implement the long keyword. It can also be applied to techniques. A 64-bit two's complement integer can put...

3 minutes read.

Java Math toDegrees() Method

The toDegrees() method of Java Math class converts a radian angle to an approximately equivalent angle measured in degrees. Syntax: public static double toDegrees(double angrad) Parameters: The parameter ‘angrad ‘represents an angle measured in...

2 minutes read.

Java Math pow() Method

The pow() method of Math class returns the value of first argument raised to the power of second argument i.e. ab. Syntax: public static double pow(double a, double b) Parameters: The parameters ‘a’ and...

3 minutes read.

Java Math expm1() Method

The expm1() method of Math class returns ex-1 where e represents Euler’s number. Syntax: public static double expm1(double x) Parameters: The parameter ‘x’ represents the exponent to raise e in the calculation of ex-1. Return...

2 minutes read.

Best Java Security Framework

The security of applications is currently our top concern when creating them. The applications or bits of code running over the network are exposed to dangers and may jeopardize integrity,...

3 minutes read.

How to Return Value from Lambda Expression Java?

What is Lambda Expression in Java? In Java 8, Lambda Expressions were introduced.A lambda expression is a brief section of code that accepts input and outputs a value. Similar to methods,...

4 minutes read.