How to Sort a List in Java 8

  • Post last modified:July 16, 2022
  • Reading time:3 mins read

How many options do we have to sort a list in Java 8?

Introduction

  • As java developers, we always need to deal with some sort of data structure to store the objects and then performing some operation such as filtering or sorting on those objects.
  • The list is often a data structure that is used to store java objects and sorting is very common to use cases performed on the list.
  • When we need to sort a list in Java, we often being lazy just do a google search, find the first StackOverflow thread, and copy-paste and customize the code.
  • In this article, I would like to jot down all the possible ways that we can sort a list in Java, so that next time we can choose the better approach and no need to copy-paste the first seen code on StackOverflow.

Collections Class

  • Java Collections class provides various methods that we can operate on collections, one of which is the sort() method which is helpful in sorting lists.
  • In the below example, we are sorting the list of customers by their age.
  • Service class returns an immutable list, but Collections.sort() expects mutable so that it can perform sorting list hence we need to convert Immutable list to mutable.
  • Using lambda we can reduce lots of boilerplate code of the comparator interface.
  • We can further improve our code by using Comparator. comparing and passing our sorting logic through method reference.
Collections.sort(modifiableCustomerList,
                   Comparator.comparing(Customer::getAge));

Sorting Collections with Stream API

Print list in reverse order using Java 8 stream API

  • Convert list to stream, then execute sorted operator. Since we need the output in reverse sorted order, let’s pass the parameter as reverseorder()

Sorting Custom Objects with Stream and Comparator

  • Here we are sorting each customer by their age, our lambda function is working since the comparator is a functional interface and the sorted operator accepts the comparator interface as input.
(a,b)-> a.getAge()-b.getAge()
  • If you write a comparator interface and implement compare logic then the code would be more verbose compare to a lambda that we wrote previously.

Conclusion

  • We have two options, we can use either Collections class or Java stream API with the Sort method.
  • When we have custom objects to sort then we have to provide the comparator implementation, we can replace it with lambda to make the code shorter and more readable. We can even simplify the code using method reference.
  • One important point to note is that the Collections class requires a modifiable list, so we cannot pass an immutable list. If we pass the immutable list then we will get an exception.
  • Hence using Stream API with sort is the better option to work with for list sorting.

Leave a Reply