How to sort a collection by using Stream API with lambdas in Java?

Java 8Object Oriented ProgrammingProgramming

A Stream API is a powerful way to achieve functional programming in Java. It usually works in conjunction with a lambda expression and provides an efficient way to perform data manipulation operations like sort, filter, map, reduce and etc.

In the below example, we can sort a collection using Stream API. It provides sorting logic by using the sorted() method of the Comparator interface. If we have two Comparator interface instances and need to do sorting by composite condition (by the first comparator and then by the second comparator), we can use both comparators by invoking the thenComparing() method on the first instance and passing in the second instance.


import java.util.*;

public class LambdaSortCollectionTest {
   public static void main(String args[]) {
      Stream<Employee> emps = Stream.of(
         new Employee("Raja"),
         new Employee("Ramesh"),
         new Employee("Surya"),
         new Employee("Jai"),
         new Employee("Adithya"));
      Comparator<Employee> c1 = Comparator.comparing(e ->;
      Comparator<Employee> c2 = (e1, e2) ->;

      List<Employee> list = emps.sorted(c1.thenComparing(c2)).collect(Collectors.toList());

// Employee class
class Employee {
   public String name;
      public Employee(String n) {
         name = n;
   public String toString() {
      return name;


[Jai, Raja, Surya, Ramesh, Adithya]
Published on 26-Dec-2019 14:35:10