This post will discuss how to sort a list of strings in lexicographical order in Java.

1. Using Collections.sort() method

A simple solution to in-place sort a list of strings in lexicographical order is using the Collections.sort() method. It takes a modifiable list, which need not be resizable.

Download  Run Code

Output:

[Amazon, Apple, Facebook, Google, Netflix]

 
The Collections.sort() method optionally takes a comparator to allow precise control over the sort order. To make the comparison between two strings case-insensitive, you can use the String.CASE_INSENSITIVE_ORDER comparator.

Download  Run Code

Output:

[Amazon, APPLE, Facebook, GOOGLE, Netflix]

2. Using List.sort() method

Another alternative to in-place sort a list of strings is with the List.sort() method, which was added to the specification in JDK 1.8. The Collections.sort() method is a wrapper over the List.sort() method. Hence, the above code is equivalent to:

Download  Run Code

Output:

[Amazon, Apple, Facebook, Google, Netflix]

 
You can use the String.CASE_INSENSITIVE_ORDER comparator to make the sort operation compare strings by ignoring their order.

Download  Run Code

Output:

[Amazon, APPLE, Facebook, GOOGLE, Netflix]

3. Using Stream.sorted() method

To create a sorted copy of the list, you can use Java 8 Stream. The idea is to create a sequential Stream over the elements in the list, sort the stream using the sorted() method, and collect all the sorted elements into a new List. This is demonstrated below:

Download  Run Code

Output:

[Amazon, Apple, Facebook, Google, Netflix]

4. Using Guava

If you happen to use the Guava library in your project, you may want to explore the Ordering class. It offers the sortedCopy() method that returns a mutable list containing elements sorted by this ordering.

Download Code

Output:

[Amazon, Apple, Facebook, Google, Netflix]

5. Using TreeSet

In a TreeSet, elements are ordered using their natural ordering or by provided Comparator. If your list contains distinct elements, you can insert all its elements into a TreeSet to get a sorted collection.

Download  Run Code

Output:

[Amazon, Apple, Facebook, Google, Netflix]

That’s all about sorting a List of strings in Java.