How to Sort String In Java
In this tutorial, we will learn how to sort String. In Java, there is not a single method inside the String class for sorting purposes. Another difficulty is Strings are immutable in Java, which means we cannot modify the original String. On the other hand, we can perform very flexible operations on an array of characters, we will be using this property of character array to sort our string.
There are two methods to sort String
- Using
Arrays.sort()
- Using Comparator in
Arrays.sort()
- Normal Sorting Using Common Algorithms like
Selection Sort
, Bubble Sort
etc.
Example of Sorting String Using Arrays.sort() Method
In the below code, the snippet original string is converted to character array by using toCharArray()
method later it is sorted using Arrays.sort()
method and then returned back to the sortedString variable which was declared earlier.
"The quick brown fox jumps over the lazy dog” is a string that contains every letter of the alphabet at least once.
import java.util.Arrays;
public class StudyTonight
{
public static void main(String[] args)
{
String originalString = "The quick brown fox jumps over the lazy dog";
String sortedString = "";
//converting string to character array
char tempString[] = originalString.toCharArray();
//perform sort using Arrays.sort() method
Arrays.sort(tempString);
//storing sorted character array back to string
sortedString = new String(tempString);
System.out.println("Original String : " + originalString);
System.out.println("Sorted String : " + sortedString);
}
}
Original String: The quick brown fox jumps over the lazy dog
Sorted String : Tabcdeeefghhijklmnoooopqrrstuuvwxyz
In the above program, you might have noticed an uppercase character is shown first it means all the capital alphabets have higher priority than lowercase alphabets. What if we want to sort without caring about the case sensitivity? In that case, we will need a custom comparator function.
Example of Sorting String Using Arrays.sort() and Comparator Function
Here, the important points to remember: we cannot add a comparator with a primitive data type that's why we created an array of Character class, and then applied the comparator function and changed the case of all the input characters to lowercase using Character.toLowerCase()
method. And at the last, we used StringBuilder
class to build a sorted string.
import java.util.Arrays;
import java.util.Comparator;
public class StudyTonight
{
public static void main(String[] args)
{
String originalString = "The quick brown fox jumps over the lazy dog";
String sortedString = "";
//length of string
int n=originalString.length();
//Building array of Character Array
Character tempString[] = new Character[n];
for (int i = 0; i < originalString.length(); i++)
{
tempString[i] = originalString.charAt(i);
}
//perform sort using Arrays.sort() with comparator function
Arrays.sort(tempString, new Comparator<Character>(){
@Override
public int compare(Character c1, Character c2)
{
//here we are converting character to lowercase
return Character.compare(Character.toLowerCase(c1),Character.toLowerCase(c2));
}
});
//StringBuilder to create string from Characters
StringBuilder sb = new StringBuilder(tempString.length);
for (Character c : tempString)
sb.append(c.charValue());
//Storing sorted string in sortedString variable
sortedString = sb.toString();
System.out.println("Original String : " + originalString);
System.out.println("Sorted String : " + sortedString);
}
}
Original String: The quick brown fox jumps over the lazy dog
Sorted String : abcdeeefghhijklmnoooopqrrsTtuuvwxyz
Now we have sorted string without the effect of case sensitivity.
Example of String Sorting Using Traditional Way Compare and Swap
After implementing sorting using the inbuilt method, can you think of a solution from scratch? So, here is an example of sorting on character array where we implemented nested loop and for each character, it will compare character on the right side of it if the smaller character is found we swap it with the current character. And after doing this as usual we will store this sorted character array in a string.
import java.util.Arrays;
public class StudyTonight
{
public static void main(String[] args)
{
String originalString = "The quick brown fox jumps over the lazy dog";
String sortedString = "";
//converting string to character array
char tempString[] = originalString.toCharArray();
int n= tempString.length;
for(int i = 0; i < n; i++ )
{
for(int j = i+1; j < n; j++)
{
if(tempString[i]>tempString[j]) {
char temp = tempString[i];
tempString[i] = tempString[j];
tempString[j] = temp;
}
}
}
//storing sorted character array back to string
sortedString = new String(tempString);
System.out.println("Original String : " + originalString);
System.out.println("Sorted String : " + sortedString);
}
}
Original String: The quick brown fox jumps over the lazy dog
Sorted String : Tabcdeeefghhijklmnoooopqrrstuuvwxyz
This is not the end of the journey. You can try those popular algorithms like Selection Sort
, Bubble Sort
etc.
Conclusion:
To sort a given string no methods are available for the String class but on the other hand, we can perform many operations on the character array. The easiest way to sort strings is using Arrays.sort()
but it is case sensitive. To avoid case sensitivity while sorting string we can use comparator functions.