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


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.

Example

import java.util.*;
import java.util.stream.*;

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 -> e.name.length());
      Comparator<Employee> c2 = (e1, e2) -> e1.name.compareTo(e2.name);

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

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

Output

[Jai, Raja, Surya, Ramesh, Adithya]

Updated on: 11-Jul-2020

366 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements