Java program to sort elements in lexicographical order (dictionary order)
:sptth//www.theitroad.com
To sort elements in lexicographical order, also known as dictionary order, in Java, you can use the sort()
method of the Arrays
class.
Here's an example program that demonstrates how to sort elements in lexicographical order in Java:
import java.util.Arrays; public class LexicographicalSort { public static void main(String[] args) { String[] words = {"apple", "banana", "cherry", "date", "elderberry"}; Arrays.sort(words); System.out.println("Words sorted in lexicographical order:"); for (String word : words) { System.out.println(word); } } }
In this program, we define a String array words
and initialize it with some sample words. We then use the Arrays.sort()
method to sort the words in lexicographical order.
After sorting the words, we use a for-each loop to iterate over the sorted words and print them to the console using the System.out.println()
method.
When you run the program, the output will be:
Words sorted in lexicographical order: apple banana cherry date elderberry
As you can see, the program successfully sorts the words in lexicographical order and prints them to the console.