Sort String In Java

Sort String In Java | There are many string operations in which we will see how to sort a string in Java, here we assemble string elements in a specified format ascending or descending. To sort strings in java there is no built-in method we have to convert them to characters and sort them.

How to Sort a String In Java

As said above there is no built-in method to sort strings in java, hence apply others methods one after another to sort strings. Strings are immutable that is they cannot be changed once created. In this section let us discuss two methods to sort strings in Java.

  1. With Arrays.sort()
  2. Without Arrays.sort()

First, we will see how to sort a string using the Arrays.sort() method:-

1) Step 1:- Import the Arrays class available in Java.
2) Step 2: Declare a method to sort the given string using the sort() method, in this method we convert the string into characters and then use the sort() method to sort the character and return sorted characters.

public static String sortString(String string) {

   // convert string to char array
   char charArray[] = string.toCharArray();

   // sort char array
   Arrays.sort(charArray);

   // return after converting char array to string 
   return new String(charArray);
}

3) Step 3:- In the main method we will take a string and call the sortString() method and pass the string as an argument and print both string and sorted string.

import java.util.Arrays;

public class Main {
   public static String sortString(String string) {
      char charArray[] = string.toCharArray();
      Arrays.sort(charArray);
      return new String(charArray);
   }

   public static void main(String[] args) {
      String string = "Know Program";
      String sortedString = sortString(string);
      System.out.println("Given String: " + string);
      System.out.println("Sorted String: " + sortedString);
   }
}

Output:

Given String: Know Program
Sorted String: KPagmnoorrw

Now, we will see how to sort without using the Arrays.sort() method. Steps to sort strings without using a pre-defined method sort():-

  1. Declare an int variable “k” and assign 0. Similarly, declare a char variable and assign 0 to it.
  2. Convert the given string to the character using toCharArray() and read all the elements by using nested for loops.
  3. If the character is greater then swap by using temporary variable temp.
  4. Convert sorted char array to String.
public class Main {
   public static void main(String[] args) {
      String string = "Know Program";
      System.out.println("Given String: " + string);
      int k = 0;
      char temp = 0;
      char[] chars = string.toCharArray();
      for (int i = 0; i < chars.length; i++) {
         for (k = 0; k < chars.length; k++) {
            if (chars[k] > chars[i]) {
               temp = chars[i];
               chars[i] = chars[k];
               chars[k] = temp;
            }
         }
      }
      String sortedString = new String(chars);
      System.out.println("Sorted String: " + sortedString);
   }
}

Output:

Given String: Know Program
Sorted String: KPagmnoorrw

Sort String Array Java

Here, we will sort a string of arrays in both ascending and descending order.

For this first, we have to import the Arrays class and Collections class. Initialize a string array to array[ ], use Arrays.sort() to sort the string array in ascending order, and use Collections.reverseOrder() to sort in descending order. Print the result. To display the array we can use Arrays.toString() method.

import java.util.Arrays;
import java.util.Collections;

public class Main {
   public static void main(String[] args) {
      String array[] = { "program", "website", "know" };
      System.out.println("String Array: " + Arrays.toString(array));

      Arrays.sort(array);
      System.out.println("Ascending  Array: " + Arrays.toString(array));

      Arrays.sort(array, Collections.reverseOrder());
      System.out.println("Descending Array: " + Arrays.toString(array));
   }
}

Output:

String Array: [program, website, know]
Ascending Array: [know, program, website]
Descending Array: [website, program, know]

Sort String Array In Java Using compareTo()

We can also sort the string array using the String class compareTo() method. Java String compareTo() method return type is an integer where it returns negative, positive, or 0 depending on the strings compared. 

import java.util.Arrays;

public class Main {
   public static void main(String args[]) {
      String[] language = 
          { "Kotlin", "JavaScript", "SQL", "Java", "Python" };
      for (int i = 0; i < language.length - 1; i++) {
         for (int j = i + 1; j < language.length; j++) {
            if (language[i].compareTo(language[j]) > 0) {
               String temp = language[i];
               language[i] = language[j];
               language[j] = temp;
            }
         }
      }
      System.out.println(Arrays.toString(language));
   }
}

Output:

[Java, JavaScript, Kotlin, Python, SQL]

Sort List Of Strings Java

To sort a list of strings, the sort() method is available in the Collections class collections framework (java.util package).

import java.util.ArrayList;
import java.util.Collections;

public class Main {
   public static void main(String[] args) {
      ArrayList<String> list = new ArrayList<String>();
      list.add("Henry");
      list.add("Albert");
      list.add("Robert");
      list.add("Harry");
      list.add("Clove");
      Collections.sort(list);
      System.out.println(list);
   }
}

Output:

[Albert, Clove, Harry, Henry, Robert]

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *