This post will discuss how to sort a List of Lists in Java.

1. Sort in lexicographical order

We can sort a list in lexicographical order using a custom comparator. The following code implements a custom comparator and passes it to List’s sort() method.

Download  Run Code

Output:

[1, 2, 1, 2]
[1, 3, 1, 2]
[1, 3, 2, 2]

2. Sort individual lists in ascending order

We can also sort individual lists in ascending order using a Comparator. The following code uses Stream API to sort each list using Comparator.naturalOrder() comparator.

Download  Run Code

Output:

[1, 2, 3]
[1, 1, 2, 2]
[1, 1, 3]

3. Sort in lexicographical and ascending order

We can merge #1 and #2 to sort the outer list in lexicographical order and inner lists in ascending order.

Download  Run Code

Output:

[1, 1, 1]
[1, 1, 2, 2]
[1, 1, 2, 3]
[1, 2, 2, 3]
[1, 2]
[2, 3]

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