Sorting of Strings is a technique in which the targeted String characters are aligned alphabetically in order. This order can be ascending or descending according to the desire. The sorting can also be applied to Strings residing inside the arrays or lists. The sorting technique enhances the user readability and presents the required data in a more structured manner.
This article describes the approaches to perform the sorting techniques over a String in Java by covering the below sections:
- Method 1: Sorting a String Using Manual Approach
- Method 2: Sorting a String Using Default Sort() Method in Java
- Method 3: Custom Sorting of String Using Sort() Method in Java
- Method 4: Sorting of String Using Java 8 Streams API and “sorted()” Method
- Method 5: Reverse Sorting of String Using “reverseOrder()” Method
- Bonus Tip: Sorting of String Type Array in Ascending and Descending Order
How to Sort a String in Java?
The sorting in Java is performed by the usage of several approaches like the built-in “sort()” method, the manual approach, the Stream API, and many more. These techniques along with their practical implementation are explained below. Let’s proceed.
Method 1: Sorting a String Using Manual Approach
The manual approach is considered less popular due to its complexity. It uses a couple of nested loops that contain the combination of temporary variable and “if” conditional statement to sort an array in desired ascending or descending order. The Java code for a specified scenario is stated below:
public class javabeat {
public static void main(String[] args) throws Exception
{
String selStr = "javabeat learning platform";
char provArray[] = selStr.toCharArray();
char tempVar;
for(int x = 0; x < provArray.length ; x += 1)
{
for (int y = x + 1; y < provArray.length; y += 1) {
if (provArray[y] < provArray[x]) {
tempVar = provArray[x];
provArray[x] = provArray[y];
provArray[y] = tempVar;
}
}
}
System.out.println("The '" + selStr + "' String has been Sorted to: ");
System.out.println(provArray);
}
}
The description of the above code is as follows:
- First, the class “javabeat” containing the “main()” method is created. Inside it, declare the targeted String “selStr” having a specified value that is required to be sorted.
- Next, the array “provArray” is declared which contains the parsed characters of the provided String.
- Now, apply the parent “for” loop containing a random “x” variable which is set to “0”. This loop iterates till the length of “provArray” and the “x” variable gets incremented by the factor of “1”.
- Then, implement the nested “for” loop which starts from one index next to “x” and it also iterates till the length of “provArray”.
- Now, If the element residing at the next index “y” is less than the element residing at index “x”. Then, swap the position of the next “y” index value with the current “x” index value using the temporary variable “tempVar”.
- This combination of nested “for” loop and “if” conditional statements will sort the String in ascending order.
- Finally, the array “provArray” containing String characters in a sorted pattern gets displayed on the console.
The generated output shows that the provided array has been sorted in the desired ascending order:
Method 2: Sorting a String Using Default Sort() Method in Java
In Java, the “sort()” method is the best candidate when it comes to performing the custom or default sorting based on ASCII values of characters. It accepts the String characters stored in the array as a parameter and returns the sorted array. Its implementation is shown below:
import java.util.Arrays;
public class javabeat {
public static String stringSorter(String provString)
{
char tempArray[] = provString.toCharArray();
Arrays.sort(tempArray);
return new String(tempArray);
}
public static void main(String[] args)
{
String provString = "javabeatlearningplatform";
String sortedString = stringSorter(provString);
System.out.println("Provided String To be Sorted: " + provString);
System.out.println("\nThe Sorted Version of Provided String: " + sortedString);
}
}
The explanation of the above code is as follows:
- First, import the “java.util.Arrays” utility using the “import” keyword and create a public class “javabeat”.
- Define a “stringSorter()” function accepting a single argument of “provString” which is required to be sorted. Parse the provided String and store each parsed character into a single array “tempArray”.
- Now, pass this “tempArray” as an argument for the “Arrays.sort()” method and return the new or modified “tempArray”.
- Next, initialize the “main()” driver method that contains our targeted string “provString”. This String is then passed as an argument for the “stringSorter()” function. This function returned the sorted version of the provided String.
- In the end, display the original String and the sorted String on the console window using the “System.out.println()” method.
The generated output shows that the String has been sorted in Java:
Method 3: Custom Sorting of String Using Sort() Method in Java
The “sort()” method can be overridden to alter the default behavior of sorting according to the ASCII-based values of each String character. This altering is done by the utilization of a “compare()” method and the “StringBuilder” class. Have a look at the below Java program for a practical demonstration of sorting a String using the “sort()” method:
import java.util.Arrays;
import java.util.Comparator;
public class javabeat {
public static String stringSorter(String provString)
{
Character tempArr[] = new Character[provString.length()];
for (int x = 0; x < provString.length(); x++) {
tempArr[x] = provString.charAt(x);
}
Arrays.sort(tempArr, new Comparator<Character>() {
@Override
public int compare(Character char1, Character char2)
{
// Converting String Characters into Single Lowercase format
return Character.compare(Character.toLowerCase(char1), Character.toLowerCase(char2));
}
});
StringBuilder builderObj = new StringBuilder(tempArr.length);
for (Character y : tempArr)
builderObj.append(y.charValue());
return builderObj.toString();
}
public static void main(String[] args)
{
String provString = "javabeatlearningplatform";
String sortedString = stringSorter(provString);
System.out.println("Provided String To be Sorted: " + provString);
System.out.println("\nThe Sorted Version of Provided String : " + sortedString);
}
}
The above code works like this:
- First, import the required “Arrays” and “Comparator” Java utilities and create a custom function “stringSorter()” inside the public class “javabeat”.
- Next, create an array “tempArr” having the length of “provString” as the new instance of the “Character” class. Apply the “for” loop and “charAt()” method to parse the String and store each parsed character in the created “tempArr” array.
- Now, pass the “temArr” and the “Comparator” class constructor as the parameters for the “Arrays.sort()” method. Then, use the “@Override” annotation to override the “compare()” method that contains two Character type parameters.
- In the “compare()” method, use the “Character.compare()” method to compare both selected String characters after converting into lowercase format. This conversion into lowercase ignores the case differentiation.
- After that, create a new object named “builderObj” for the “StringBuilder” class and utilize the enhanced “for” loop that iterates over the “tempArr”.
- In addition, it uses the “append()” method to join each sorted String Character and return it after final conversion into String.
- In the end, initialize the driver “main()” method that contains the targeted String in the “provString” variable. This variable is then passed as a parameter for the “stringSorter()” function to perform the sorting.
- The original provided String and the sorted String are then displayed on the console window for verification purposes.
The generated output for the above code shows that the provided String has been Sorted:
Method 4: Sorting of String Using Java 8 Streams API and “sorted()” Method
The “sorted()” method provided by Java 8 Streams API is utilized to sort the provided String after its conversion into the List. The code to perform the sorting using the mentioned method is shown below:
public class javabeat
{
public static void main(String[] args)
{
String provString = "javabeat learning platform";
String sortedString = provString.chars().sorted().collect(
StringBuilder::new,
StringBuilder::appendCodePoint,
StringBuilder::append
).toString();
System.out.println("Provided String To be Sorted: " + provString);
System.out.println("\nThe Sorted Version of Provided String : " + sortedString);
}
}
The explanation for the above code is as follows:
- First, create a class “javabeat” containing the “main()” method. Inside the “main()” method declare and initialize a dummy String type variable “provString”.
- The “chars()” method is then assigned with the “provString” variable that converts the String into the list format. Then, the “sorted()” method is applied to perform the sorting over the list elements.
- After that, the “collect()” method containing the “StringBuilder” is used to perform a mutable reduction operation over the sorted list. This method repacks or folds the list into the String type variable named “sortedString”.
- Finally, display the original and sorted String over the console by invoking the “System.out.println()” method.
The generated output shows that the provided String has been sorted using the Stream API sorted() method:
Method 5: Reverse Sorting of String Using “reverseOrder()” Method
To sort the provided String Characters in lexicographically decreasing order in Java, the “reverseOrder()” method of the “Collections” utility is utilized. This method is passed as the second parameter of an “Arrays.sort()” method to convert the sorted result in reverse order. The code to implement the discussed scenario is shown below:
import java.util.Arrays;
import java.util.Collections;
public class javabeat {
public static void main(String[] args)
{
String provString = "javabeatlearningplatform";
Character tempArr[] = new Character[provString.length()];
for (int x = 0; x < provString.length(); x++) {
tempArr[x] = provString.charAt(x);
}
// Reverse the order using Collections.reverseOrder() argument
Arrays.sort(tempArr, Collections.reverseOrder());
StringBuilder sortedString = new StringBuilder(tempArr.length);
for (Character y : tempArr)
{
sortedString.append(y.charValue());
}
System.out.println("Provided String To be Sorted: " + provString);
System.out.println("\nThe Reverse Sorted Version of String: " + sortedString.toString());
}
}
The above code works like this:
- First, import the “Arrays” and “Collections” Java utilities using the “import” keyword and define the main “javabeat” class.
- Inside it, declare and initialize the random “provString” String and create an empty array “tempArr” as an object of the “Character” class.
- Next, utilize the “for” loop that iterates over the “tempArr” and stores the parsed String characters in each index of the array.
- After that, invoke the “Arrays.sort()” method having the “tempArr” array and the “Collections.reverseOrder()” method as parameters.
- In addition, create a new instance “sortedString” of the “StringBuilder” class and apply the enhanced “for” loop. Inside the loop, the “append()” method is used to insert the reverse order sorted String characters into the “sortedString” instance.
- Finally, display the original and sorted String on the console for verification purposes.
The generated output shows the String has been sorted in the reverse order:
Bonus Tip: Sorting of String Type Array in Ascending and Descending Order
The Array of String can also be sorted in the desired ascending or descending order. By sorting a String Array, each element of the array gets aligned according to its alphabetical order. The method that is used to sort String Array is “Arrays.sort()” and the implementation procedure is mentioned below:
import java.util.Arrays;
import java.util.Collections;
public class javabeat {
public static void main(String[] args)
{
//Provided String Array
String[] provString = {"Olivia", "Sophia", "Aubrey", "Amelia", "Hannah", "Evelyn", "Harper", "Camila"};
System.out.println("Provided String To be Sorted: " + Arrays.toString(provString));
//sorts the string array in ascending order
Arrays.sort(provString);
System.out.println("\nThe Sorted Version of String: " + Arrays.toString(provString));
//sorts the string array in descending order
Arrays.sort(provString, Collections.reverseOrder());
System.out.println("\nThe Reverse Sorted Version of String Array: " + Arrays.toString(provString));
}
}
The above code works like this:
- First, the “Arrays” and “Collections” utilities are imported and the class “javabeat” containing the “main()” method is also created.
- Next, declare and initialize the String type array “provString” with random String values.
- Now, to sort the String array in ascending order the “provString” is passed as an argument in the “Arrays.sort()” method. The modified “provString” array is then displayed on the console after converting into String format using the “Arrays.toString()” method.
- After that, pass the “provString” and “Collections.reverseOrder()” as parameters to the “Arrays.sort()” method to sort the String array elements in descending or reverse order.
- Finally, convert the “provString” array into a String using the “Arrays.toString()” method.
The output for the above code snippet shows that String array elements are sorted in the desired order:
That’s all about the sorting of a String in Java.
Conclusion
To sort a String in Java, the user can use the “sort()” method with default and custom parameters, “Java 8 Streams API”, “reverseOrder()” method provided by the collection utility, or can define a custom method using loops and conditional statements. For the “sort()” method, pass the array of parsed Strings as its parameter, for the “StreamAPI”, use its provided “sorted()” method. To sort the order in reverse order, pass the sorted array inside the “reverseOrder()” method. This guide has explained the approaches to sorting a String in Java.