Sorting a List using Lambda Expression in Java 8 - Java @ Desk

Saturday, July 22, 2017

Sorting a List using Lambda Expression in Java 8

Sorting a List using Lambda Expression in Java 8

In this post, we will learn how to sort a list using Lambda Expression in Java 8. In Java 6 or 7, Java pojo object must implements Comparator interface or Comparable interface to sort a collection of objects. The implementation need to be provided in compareTo method to sort a list based on particular property of a class.

In Java 8, the code has been reduced to just a single line. One can use the below 3 implementations:
1) sort method of List interface
2) sort method of Collections class
3) sort using stream() method of List interface

In 3rd strategy, the underlying list does not get sorted. So, either you must create a new object and assign the sorted list or assign the sorted list to the existing list object.
In both the implementations, the sorting logic goes as a Lambda expression.

Consider a Person class below in which sorting logic needs to be implemented on name of the person.
package com.pojo;

public class Person {

 private String id;

 private String name;

 private String address;

 public Person(String id, String name, String address) {
  super(); = id; = name;
  this.address = address;

 public String getId() {
  return id;

 public void setId(String id) { = id;

 public String getName() {
  return name;

 public void setName(String name) { = name;

 public String getAddress() {
  return address;

 public void setAddress(String address) {
  this.address = address;

 public String toString() {
  return + ", " + + ", " + this.address;
Below one is the traditional sorting technique
Collections.sort(persons, new Comparator<Person>() {
   public int compare(Person p1, Person p2) {
    return p1.getName().compareTo(p2.getName());

Here is the implementation using Java 8 using Lambda expression
Collections.sort(persons, (p1, p2) -> p1.getName().compareTo(p2.getName()));

Collections.sort(persons, (Person p1, Person p2) -> p1.getName().compareTo(p2.getName()));

persons.sort((p1, p2) -> p1.getName().compareTo(p2.getName()));

// Here, specifically the sorted list need to be assigned to a new list
// or existing list object.  
persons =, p2) -> (p.getName().compareTo(p2.getName())))

Finally print the list using lambda expression
persons.forEach((person) -> System.out.print(person + "\n"));

IdOne, Andy, Netherland
IdThree, Chris, London
IdTwo, John, Australia
IdFour, Nathan, Paris
IdFive, Peter, Brazil

No comments:

Post a Comment