Sorting a String in Java
Sorting a String in Java
Sorting is a process of arranging available data objects in a meaningful format that is ascending or descending order. Sorting a string or array of String objects can be used to check if two strings are composed of similar alphabets. In Java, there are several methods available for sorting strings.
How to sort a String in Java
Java provides the following ways to sort a string:
- Using for Loops
The basic logical programming approach for sorting anarray of elements is to use nested for loops. Inside the for loops we have used an if statement.Inside the if statement, we have compared the elements. If the condition returns true, it performs swapping and sort the elements, accordingly.
SortwLoop.java
import java.util.*; public class SortwLoop { /* Driver Code */ public static void main(String []args) { /* Unsorted order */ String[] fruits = {"Grapes", "Banana", "Apple", "Jackfruit"}; System.out.println("Before Sorting: "+(Arrays.toString(fruits))); /* Nested for loop to compare one string with another */ for (int i = 0; i < fruits.length; i++) { for (int j = i + 1; j < fruits.length; j++) { /* if condition to compare each element of String array with rest elements */ if (fruits[i].compareTo(fruits[j])>0) { /*Swapping strings */ String temp = fruits[i]; fruits[i] = fruits[j]; fruits[j] = temp; } } } /* Sorted order */ System.out.println("After Sorting: "+(Arrays.toString(fruits))); } }
Output:
Before Sorting: [Grapes, Banana, Apple, Jackfruit] After Sorting: [Apple, Banana, Grapes, Jackfruit]
In the above code snippet, the main()method consist an array of String objects fruits. The first for loop start with 0th element and compares it with rest of the elements of String array fruitsusing the inner for loop. After the first iteration of outer for loop is complete, first element gets its correct position and the loop continues until the condition becomes false.
- Using Arrays.sort() Method
Arrays class belongs to java.util package. The class defines sort() method that performs sorting of an array in ascending order. Sorting using Arrays.sort() requires fewer lines of code.
SortwArraysort.java
import java.util.*; public class SortwArraysort { /* Driver Code */ public static void main(String []args) { /* Unsorted order */ String[] cities = {"Mumbai", "Banglore", "Surat", "Delhi", "Chennai"}; System.out.println("Before Sorting: "+(Arrays.toString(cities))); /* sort() method */ Arrays.sort(cities); /*Sorted order */ System.out.println("After Sorting: "+(Arrays.toString(cities))); } }
Output:
Before Sorting: [Mumbai, Banglore, Surat, Delhi, Chennai] After Sorting: [Banglore, Chennai, Delhi, Mumbai, Surat]
Here, an array of String objects is declared i.e., cities. The Arrays.sort() method takes one argument cities. It is a static method,so we can call it directly by suing the class name. It does not return any value.
- Using List.sort() Method
The Java List interface provides a sort() method. It can be used to sort a list of String objects. The following program demonstrates use of sort() method.
SortwListsort.java
import java.util.*; public class SortwListsort { /* Driver Code */ public static void main(String []args) { /* Unsorted list */ List<String> color = Arrays.asList("Cyan", "Black", "Red", "Yellow", "Green"); System.out.println("Before Sorting: "+color); System.out.println("After Sorting: "); /* Ascending Order */ color.sort( Comparator.comparing( String::toString ) ); System.out.println("1. Ascending order: "+color); /* Descending Order */ color.sort( Comparator.comparing( String::toString ).reversed() ); System.out.println("2. Descending order: "+color); } }
Output:
Before Sorting: [Cyan, Black, Red, Yellow, Green] After Sorting: 1. Ascending order: [Black, Cyan, Green, Red, Yellow] 2. Descending order: [Yellow, Red, Green, Cyan, Black]
Here, the list of String objects color is in unsorted form. The sort() method arranges the objects into ascending and descending order.
- Using Collections.sort() Method
The java.util.Collections package defines a sort() method that is similar to the Arrays.sort() method. But it has an advantage, Collections.sort() method can sort elements of Array and also other data structures like queue, linked list, etc.
SortwCollection.java
import java.util.*; public class SortwCollection { /* Driver Code */ public static void main(String []args) { /* Unsorted list of Strings */ List<String> fruits = Arrays.asList("Grapes", "Banana", "Apple", "Jackfruit"); /* Ascending order */ Collections.sort(fruits); System.out.println("Ascending order: "+fruits); /* Descending order */ Collections.sort(fruits, Collections.reverseOrder()); System.out.println("Descending order: "+fruits); } }
Output:
Ascending order: [Apple, Banana, Grapes, Jackfruit] Descending order: [Jackfruit, Grapes, Banana, Apple]
Here, the list of String objects fruits is in unsorted form. The Collections.sort() method arranges the objects into ascending order and Collections.reverseOrder() method into descending order.
- Using Java Stream (available in Java 8)
In Java 8, the Stream API is available. Stream API provides a way to sort String objects using ASCII values of the alphabets.
SortwStream.java
import java.util.stream.Collectors; import java.util.stream.Stream; public class SortwStream { /* Driver Code */ public static void main(String[] args) { /* Unsorted string */ String str = "CADB"; System.out.println("Unsorted String: "+str); /* Sorting operation */ str = Stream.of(str.split("")).sorted().collect(Collectors.joining()); /* Sorted String */ System.out.println("Sorted String: "+str); } }
Output:
Unsorted String: CADB Sorted String: ABCD
Here, the String stris declared. The Stream API, first splits the string and then performs sorting according to the ASCII values.
This article discusses various methods available in Java, for sorting an array of String with examples.