BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Java 8 Lambda Comparator example for Sorting List of Custom Objects

Last Updated: September 11, 2022 by Chaitanya Singh | Filed Under: java

We have already seen how to sort an Arraylist of custom Objects without using lambda expression. In this tutorial we will see how to sort a list of custom objects using lambda expression in Java.

Before we see the complete example, lets see what is the difference between using lambda vs without using lambda:

Without using Lambda expression: Before Java 8 we sort like this:

If you are not familiar with the Comparator, refer this guide: Java Comparator with example.

Here we are sorting a list of objects of Student class by name.

Comparator sortingByName = new Comparator() {
   @Override
   public int compare(Student s1, Student s2) {
	return s1.getName().compareTo(s2.getName());
   }
};

Using Lambda expression: The Java 8 equivalent code using Lambda expression would look like this:

Comparator sortingByName =
(Student s1, Student s2)->s1.getName().compareTo(s2.getName());

Note: In Java 8, the List interface supports the sort() method so you need not to use the Comparator.sort(), instead you can use the List.sort() method. The above code can be further re-written as:
Here studentlist is the instance of the list containing Student objects (see the complete example below).

studentlist.sort((Student s1, Student s2)->s1.getName().compareTo(s2.getName()));

Java 8 – Sorting with Lambda Expression

import java.util.ArrayList;
import java.util.List;
class Student {
   String name; 
   int age; 
   int id; 
   public String getName() {
      return name; 
   } 
   public int getAge() { 
      return age; 
   } 
   public int getId() { 
      return id; 
   } 
   Student(String n, int a, int i){ 
      name = n; 
      age = a; 
      id = i; 
   } 
   @Override public String toString() {     
      return ("Student[ "+"Name:"+this.getName()+             
              " Age: "+ this.getAge() +                     
              " Id: "+ this.getId()+"]"); 
   }
}
public class Example {
   public static void main(String[] args) {
      List<Student> studentlist = new ArrayList<Student>();
      studentlist.add(new Student("Jon", 22, 1001)); 
      studentlist.add(new Student("Steve", 19, 1003)); 
      studentlist.add(new Student("Kevin", 23, 1005)); 
      studentlist.add(new Student("Ron", 20, 1010)); 
      studentlist.add(new Student("Lucy", 18, 1111));
      System.out.println("Before Sorting the student data:"); 
 
      //java 8 forEach for printing the list 
      studentlist.forEach((s)->System.out.println(s));

      System.out.println("After Sorting the student data by Age:"); 

      //Lambda expression for sorting by age 
      studentlist.sort((Student s1, Student s2)->s1.getAge()-s2.getAge()); 

      //java 8 forEach for printing the list
      studentlist.forEach((s)->System.out.println(s));         

      System.out.println("After Sorting the student data by Name:"); 
      //Lambda expression for sorting the list by student name       
      studentlist.sort((Student s1, Student s2)->s1.getName().compareTo(s2.getName())); 
      studentlist.forEach((s)->System.out.println(s));        
      System.out.println("After Sorting the student data by Id:");        
      //Lambda expression for sorting the list by student id 
      studentlist.sort((Student s1, Student s2)->s1.getId()-s2.getId()); 
      studentlist.forEach((s)->System.out.println(s)); 
   }
}

Output:

Before Sorting the student data:
Student[ Name:Jon Age: 22 Id: 1001]
Student[ Name:Steve Age: 19 Id: 1003]
Student[ Name:Kevin Age: 23 Id: 1005]
Student[ Name:Ron Age: 20 Id: 1010]
Student[ Name:Lucy Age: 18 Id: 1111]

After Sorting the student data by Age:
Student[ Name:Lucy Age: 18 Id: 1111]
Student[ Name:Steve Age: 19 Id: 1003]
Student[ Name:Ron Age: 20 Id: 1010]
Student[ Name:Jon Age: 22 Id: 1001]
Student[ Name:Kevin Age: 23 Id: 1005]

After Sorting the student data by Name:
Student[ Name:Jon Age: 22 Id: 1001]
Student[ Name:Kevin Age: 23 Id: 1005]
Student[ Name:Lucy Age: 18 Id: 1111]
Student[ Name:Ron Age: 20 Id: 1010]
Student[ Name:Steve Age: 19 Id: 1003]

After Sorting the student data by Id:
Student[ Name:Jon Age: 22 Id: 1001]
Student[ Name:Steve Age: 19 Id: 1003]
Student[ Name:Kevin Age: 23 Id: 1005]
Student[ Name:Ron Age: 20 Id: 1010]
Student[ Name:Lucy Age: 18 Id: 1111]

Java 8 – Sorting in reverse order

To sort the list in the reverse(descending) order, just change the order of the arguments like this:

Sorting the list of objects of Student class by Name in reverse order:

studentlist.sort((Student s1, Student s2)->s2.getName().compareTo(s1.getName()));

Similarly, the list can be sorted in reverse order by student age and id like this:

//Lambda expression for sorting the list by student age in reverse order 
studentlist.sort((Student s1, Student s2)->s2.getAge()-s1.getAge());
//Lambda expression for sorting the list by student id in reverse order 
studentlist.sort((Student s1, Student s2)->s2.getId()-s1.getId());

Related Tutorials:

  1. Java 8 – Arrays Parallel Sort Example
  2. Java – sort ArrayList in descending order
  3. Java – sort HashMap by keys and Values
  4. Java – bubble sort in ascending and descending order

Top Related Articles:

  1. Java 8 forEach method with example
  2. Multilevel inheritance in java with example
  3. Java 8 – Get Current Date and Time
  4. How to Convert an array to ArrayList in java
  5. Comparable Interface in Java with example

Tags: Java8-Features

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap