Open In App

Java Program to Sort an Array of Strings in Lexicographical Order (Dictionary Order)

Last Updated : 25 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Java, sorting an array in lexicographical (dictionary) order means elements will be arranged based on their alphabetical order from A to Z with case sensitivity.

Example:

We will use Arrays.sort() method with String.CASE_INSENSITIVE_ORDER to sort an array in lexicographical order. It is the most direct and common method to sort an array in lexicographical order with case-insensitive.

Java
// Java Program to Sort Elements in
// Lexicographical Order (Dictionary Order)
import java.io.*;
import java.util.Arrays;

class GFG {
    
    // this function prints the array passed as argument
    public static void print(String arr[]) {
      
        for (String s : arr)
            System.out.print(s + " ");
        System.out.println();
    }
  
    public static void main(String[] args)
    {
        // Initializing String array
        String arr2[]
            = { "Rat", "Dog", "Cat" };

        // sorting String array in Lexicographical Order
        // Ingonring case case while sorting using CASE_INSENSITIVE_ORDER
        Arrays.sort(arr2,
                    String.CASE_INSENSITIVE_ORDER);
      
        print(arr2);
    }
}

Output
Cat Dog Rat 

Explanation: The Arrays.sort(arr2, String.CASE_INSENSITIVE_ORDER) sorts the array arr2 lexicographically by ignoring case. The String.CASE_INSENSITIVE_ORDER is a built-in comparator that sorts the string without considering the case (uppercase or lowercase).

Other Ways to Sort an Array of Strings in Lexicographical Order

Using compareToIgnoreCase()

In this example, we will manually compare strings using the compareToIgnoreCase() method from the String class. This method compares two strings lexicographically, ignoring case differences.

Java
// Java Program to Sort Elements in 
// Lexicographical Order (Dictionary Order)
import java.io.*;

class GFG {

    // this method sorts the string array lexicographically
    public static void sort(String s[]) {
      
        for (int i = 0; i < s.length; i++) {
          
            for (int j = i + 1; j < s.length; j++) {
              
                if (s[i].compareToIgnoreCase(s[j]) > 0) {
                    String temp = s[i];
                    s[i] = s[j];
                    s[j] = temp;
                }
            }
        }
    }

    // this function prints the array passed as argument
    public static void print(String s[]) {
        for (String s1 : s) 
            System.out.print(s1 + " ");
        System.out.println();
    }

    public static void main(String[] args) {
      
        // Initializing String array
        String arr[] = { "Rat", "Dog", "Cat" };

        // sorting String array lexicographically
        sort(arr);

        print(arr);
    }
}

Output
Cat Dog Rat 


Using a Custom Comparator

In this approach, we can define our own custom comparator to sort array of strings in lexicographical order. This provides more flexibility and this method allow to customize how the strings should be compared.

Java
// Java Program to Sort Elements 
// in Lexicographical Order (Dictionary Order)
import java.util.*;

public class ArrayOfStringSort {
  
    public static void main(String[] args) {
      
        String[] sa = { "Rat", "Dog", "Cat" };
        
        // Sorting using a custom comparator
        Arrays.sort(sa, (a, b) -> a.compareToIgnoreCase(b));

        for (String s : sa) {
            System.out.print(s + " ");
        }
    }
}

Output
Cat Dog Rat 


Using Stream API (Java 8 and Above)

We can use Stream API, which can be used in Java 8 or above version to sort the strings in lexicographical order. The Stream.sorted() method specifies a comparator and the sorted result collected back into an array.

Java
// Java Program to Sort Elements in 
// Lexicographical Order (Dictionary Order)
import java.util.*;
import java.util.stream.*;

public class ArraysOfStringSort {
  
    public static void main(String[] args) {
        String[] sa = { "Rat", "Dog", "Cat" };

        // sort using Stream API with CASE_INSENSITIVE_ORDER
        String[] arr = Arrays.stream(sa)
                                      .sorted(String.CASE_INSENSITIVE_ORDER) // using a comparator for case-insensitive sorting
                                      .toArray(String[]::new);  // collect back into an array
        
        for (String s : arr) {
            System.out.print(s + " ");
        }
    }
}

Output
Cat Dog Rat 

Note:

  • The Stream.sorted() method does not modify the original stream. It returns a new sorted stream.
  • If we do not provide a comparator, it will sort the stream using the natural ordering of the elements i.e. using Comparable.


Similar Reads