How to Sort String in Java Alphabetically

Sorting string in Java is a common task in programming. For example, we may need to sort a list of items sold by online store, or a list of customer names and email addresses.

Sorting is an algorithmic technique to put all strings in certain alphabetical order or natural order. It is very helpful for solving real-world problems.

String class in Java doesn’t provide any method that directly sorts a list of strings. There are two methods with which we can sort string in Java alphabetically:

  • Using user-defined logic (Without using sort() method)
  • With using sort() method

Using User defined Logic


We will sort a string array by comparing each element with other elements. Let’s take an example program in which we will take a group of elements into an array and sort them into ascending order.

We will use swapping technique in which we will compare the first of the array with the immediate element. If it is bigger than immediate element, then they are swapped (interchanged).

Since we are sorting in ascending order, we expect the smaller elements to be in the first place. When two elements are swapped or interchanged, the number of elements to be sorted becomes lesser by 1. Let’s write the complete code for it.

Program code 1:

package stringPrograms;
import java.util.Arrays;
public class SortingString {
public static void main(String[] args) 
{
// Creating an array of String.  
   String[] countries = {"USA", "South-Africa", "India", " Australia", "Denmark", "France", "Italy", "Germany"};  
   int size = countries.length;  

// User defined logic to sort string array.
// Applying nested for loop.   
   for(int i = 0; i < size - 1; i++)   
   {  
     for (int j = i+1; j < countries.length; j++) 
     { 
     // Comparing each element of the array with the rest elements. 
        if(countries[i].compareTo(countries[j])>0)   
	{  
	// Swapping array elements  
	   String temp = countries[i];  
	   countries[i] = countries[j];  
	   countries[j] = temp;  
	}  
    }
 }
// Displaying the sorted array in alphabetical order.  
   System.out.println(Arrays.toString(countries));     
 }
}
Output:
      [ Australia, Denmark, France, Germany, India, Italy, South-Africa, USA]

Using Arrays.sort() Method


In Java, Arrays class defined in the java.util package provides a static method named sort() to sort an array in ascending order. It uses an algorithm named Dual-Pivot Quicksort for sorting.

Its complexity is O(n log(n)). Since it is a static method that parses an array as a parameter and returns nothing. We can directly call it by using the class name. It accepts an array of primitive types, such as int, float, double, long, char, byte. The general syntax of using this method is:

public static void sort(int[] a)

Where a is an array to be short.


Note: Like Arrays class, Java Collections class also provides a sort() method to sort the array. But there is a difference between them.

The sort() method of Arrays class is applicable for primitive type while the sort() method of the Collections class is applicable for objects Collections, such as ArrayList, LinkedList, etc.


We can perform sorting of an array in the following ways:

  • Ascending Order or Alphabetical Order or Natural Order
  • Descending Order or Reverse Natural Order

How to Sort String in Java Alphabetically or Ascending Order


Alphabetical order is a natural order or ascending order in which elements arrange in the lowest to the highest. Let’s take an example program in which we will sort string array using the sort() method of the Arrays class.

Program code 2:

package stringPrograms;
import java.util.Arrays;
public class AscOrder {
public static void main(String[] args) 
{
// Creating an array of String.  
   String[] fruits = {"Orange", "Banana", "Guava", "Papaya", "Apple", "Mango"};  

// Sorting string array in alphabetical order or ascending order  
   Arrays.sort(fruits);  

// Displays the sorted string array in ascending order. 
   System.out.println("Sorting elements in alphabetical order: ");
   System.out.println(Arrays.toString(fruits));     
 }
}
Output:
     Sorting elements in alphabetical order: 
     [Apple, Banana, Guava, Mango, Orange, Papaya]

Sorting String Array in Descending Order or Reverse Natural Order


Java Collections class provides a static method named reverseOrder() to sort the array in reverse-lexicographic order. Since it is a static method, so we can call it directly by using the class name.

The reverseOrder() method does not accept any parameter. It returns a comparator that reverse elements in the natural ordering (ascending order).

It means that the sort() method sorts array elements in the ascending order, after that reverseOrder() method reverses the natural ordering. Thus, we get the sorted array elements in descending order. The general syntax of using reverseOrder() method is as:

public static <T> Comparator<T> reverseOrder()

Suppose x[ ] is an array of elements to be sorted in the descending order. We will use reverseOrder() method of Collections class in the following ways:

Arrays.sort(x, Collections.reverseOrder());

Let’s take an example program in which we will sort a string array in the descending order.

Program code 3:

package stringPrograms;
import java.util.Arrays;
import java.util.Collections;
public class DescOrder {
public static void main(String[] args) 
{
// Creating an array of String.  
   String[] cities = {"Dhanbad", "New York", "Sydney", "Cape town", "Paris", "Moscow"};  

// Sorting string array in descending order.  
   Arrays.sort(cities, Collections.reverseOrder());   

// Displays the sorted string array in descending order.
   System.out.println("Sorted string array in descending order: ")
   System.out.println(Arrays.toString(cities));   
 }
}
Output:
      Sorted string array in descending order: 
      [Sydney, Paris, New York, Moscow, Dhanbad, Cape town]

In this tutorial, we have explained how to sort string elements in ascending or descending order alphabetically in Java. Hope that you will have understood the basic methods of sorting string alphabetically. In the next tutorial, we will learn anagram in Java and how to check it.
Thanks for reading!!!

⇐ PrevNext ⇒

Please share your love