- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to write the comparator as a lambda expression in Java?
A lambda expression is an anonymous method and doesn't execute on its own in java. Instead, it is used to implement a method defined by the functional interface. A lambda expression used with any functional interface and Comparator is a functional interface. The Comparator interface has used when sorting a collection of objects compared with each other.
In the below example, we can sort the employee list by name using the Comparator interface.
Example
import java.util.ArrayList; import java.util.Collections; import java.util.List; class Employee { int id; String name; double salary; public Employee(int id, String name, double salary) { super(); this.id = id; this.name = name; this.salary = salary; } } public class LambdaComparatorTest { public static void main(String[] args) { List<Employee> list = new ArrayList<Employee>(); // Adding employees list.add(new Employee(115, "Adithya", 25000.00)); list.add(new Employee(125, "Jai", 30000.00)); list.add(new Employee(135, "Chaitanya", 40000.00)); System.out.println("Sorting the employee list based on the name"); // implementing lambda expression Collections.sort(list, (p1, p2) -> { return p1.name.compareTo(p2.name); }); for(Employee e : list) { System.out.println(e.id + " " + e.name + " " + e.salary); } } }
Output
Sorting the employee list based on the name 115 Adithya 25000.0 135 Chaitanya 40000.0 125 Jai 30000.0
- Related Articles
- How can we write Callable as a lambda expression in Java?
- How to write a conditional expression in lambda expression in Java?
- How can we write a multiline lambda expression in Java?
- How to write lambda expression code for SwingUtilities.invokeLater in Java?
- How to pass a lambda expression as a method parameter in Java?
- Java Program to pass lambda expression as a method argument
- How to declare a variable within lambda expression in Java?
- How to reverse a string using lambda expression in Java?
- How to use BooleanSupplier in lambda expression in Java?
- How to use IntSupplier in lambda expression in Java?
- How to implement a lambda expression in JShell in Java 9?
- How to use a return statement in lambda expression in Java?
- How to implement IntBinaryOperator using lambda expression in Java?
- How to implement ToIntBiFunction using lambda expression in Java?
- How to implement ToDoubleBiFunction using lambda expression in Java?

Advertisements