Write a Java Program to Sort Elements in Lexicographical Order

In Java, we can easily sort a list of elements in lexicographical order using the built-in Collections class.

Lexicographical order is a type of ordering that is based on the alphabetical order of the elements in the list.


Here’s a simple Java program that demonstrates how to sort a list of strings in lexicographical order:

import java.util.ArrayList;
import java.util.Collections;

public class LexicographicalOrder {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<String>();
        list.add("cat");
        list.add("dog");
        list.add("bird");
        list.add("fish");

        System.out.println("Before sorting: " + list);

        Collections.sort(list);

        System.out.println("After sorting: " + list);
    }
}

In this program, we first create an ArrayList of strings and add four elements to it.

We then print the list before sorting to show its original order.

Finally, we use the Collections.sort() method to sort the list in lexicographical order and print the sorted list.

The output of this program will be:

Before sorting: [cat, dog, bird, fish]
After sorting: [bird, cat, dog, fish]

As you can see, the elements in the list are now in lexicographical order based on their alphabetical order.


In conclusion, sorting a list of elements in lexicographical order in Java is very easy using the Collections class.

By following the above example, you can easily sort your own lists in lexicographical order in your Java programs.