To sort a list of strings in Java in dictionary order, you can use the `Collections.sort` method.
In this example,
java.util.Collections
and java.util.List
.words1
with some strings.Collections.sort
method to sort the list in dictionary order.import java.util.Collections;
import java.util.List;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
List<String> words1 = new ArrayList<>();
words1.add("banana");
words1.add("apple");
words1.add("grape");
words1.add("orange");
Collections.sort(words1);
System.out.println("Sorted list 1 in dictionary order: " + words1);
}
}
Sorted list 1 in dictionary order: [apple, banana, grape, orange]
In this example,
words2
with different strings.Collections.sort
method to sort this list in dictionary order.import java.util.Collections;
import java.util.List;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
List<String> words2 = new ArrayList<>();
words2.add("pear");
words2.add("kiwi");
words2.add("lemon");
words2.add("apple");
Collections.sort(words2);
System.out.println("Sorted list 2 in dictionary order: " + words2);
}
}
Sorted list 2 in dictionary order: [apple, kiwi, lemon, pear]
In this tutorial, we learned How to Sort a List of Strings in Dictionary Order in Java language with well detailed examples.