Summary: In this tutorial, we will learn different ways to sort an array or list of strings in alphabetical order using the Java programming language.

Example:

Input:   ["Python", "Java", "C", "JavaScript", "C++"]
Output:  ["C", "C++", "Java", "JavaScript", "Python"]

Note: Alphabetical order is also known as dictionary or lexicographical order.

Method 1: Using compareTo()

The compareTo() method in Java returns the lexicographical difference between two Strings (i.e. difference in dictionary order).

It returns a positive integer if first string comes after the second string in the dictionary, otherwise a negative number.

Example:

String str1 = "A", str2 = "B";
str1.compareTo(str2);          // returns -1

String str1 = "C", str2 = "B";
str1.compareTo(str2);          // returns -1

String str1 = "ad", str2 = "ab";
str1.compareTo(str2);          // returns 2

String str1 = "A", str2 = "a";
str1.compareTo(str2);          // returns 2

Note: The compareTo() method treats ]upper case (e.g. A) and lower case (e.g. a) differently.

So to sort strings in alphabetical order, we compare them using the compareTo() and sort using the bubble sort algorithm (just like integers).

class Main {
  public static void main(String[] args) {
    //array of strings
    String names[] = {"Python", "Java", "C", "JavaScript", "C++"};
 
    for(int i=0; i<names.length-1; i++){
      for(int j=0; j<names.length-1-i; j++){
        //tranform strings to lowercase for correct comparision
        String str1 = names[j].toLowerCase();
        String str2 = names[j+1].toLowerCase();
        
        //find difference using compareTo()
        if(str1.compareTo(str2)>0){
          //if difference is +ve, then swap
          String temp = names[j];
          names[j] = names[j+1];
          names[j+1] = temp;
        }
 
      }
    }
 
    //output the sorted array
    for(int i=0; i<names.length; i++){
      System.out.print(names[i]+" ");
    }
 
  }
}

Output:

C C++ Java JavaScript Python

Method 2: Using Collections.sort()

We can also use the sort() method of the Collections class (available in java.util package) to sort strings in alphabetical order, but strings should be in a list instead of an array.

import java.util.Arrays;
import java.util.List;
import java.util.Collections;
 
class Main {
  public static void main(String[] args) {
 
    //creating a list of strings
    List<String> nameList = Arrays.asList("Python", "Java", "C", "JavaScript", "C++");
 
    //sorting the list
    Collections.sort(nameList);
 
    //output the sorted list
    for(String name: nameList){
      System.out.print(name+" ");
    }
  }
}

Output:

C C++ Java JavaScript Python

Leave a Reply