Sort the words in lexicographical order in Java

Java 8Object Oriented ProgrammingProgramming

The words are sorted in lexicographical order or dictionary order. This means that the words are alphabetically ordered based on their component alphabets. An example of this is given as follows.

The original order of the words is
Tom
Anne
Sally
John
The lexicographical order of the words is
Anne
John
Sally
Tom

A program that demonstrates this is given as follows.

Example

 Live Demo

public class Example {
   public static void main(String[] args) {
      String[] words = { "Peach", "Orange", "Mango", "Cherry", "Apple" };
      int n = 5;
      System.out.println("The original order of the words is: ");
      for(int i = 0; i < n; i++) {
         System.out.println(words[i]);
      }
      for(int i = 0; i < n-1; ++i) {
         for (int j = i + 1; j < n; ++j) {
            if (words[i].compareTo(words[j]) > 0) {
               String temp = words[i];
               words[i] = words[j];
               words[j] = temp;
            }
         }
      }
      System.out.println("\nThe lexicographical order of the words is: ");
      for(int i = 0; i < n; i++) {
         System.out.println(words[i]);
      }
   }
}

Output

The original order of the words is:
Peach
Orange
Mango
Cherry
Apple
The lexicographical order of the words is:
Apple
Cherry
Mango
Orange
Peach
raja
Published on 07-Dec-2018 07:11:49
Advertisements