Java 8 – Comparison with Lambda

Before Java 8 sorting of a collection of custom, classes require a lot of code to define the sorting strategy using one of the interfaces provided in Java. We can either use java.lang.Comparable or java.util.Comparator. But since the inception of Java-8, we can reduce the lines of code using a lambda expression.

Lambda expression

In this tutorial, we will look at Java 8 Lambda support specifically at how to use it to write the Comparator and sorting of a Collection.

Let’s start it by creating an entity class we will be using in our example.

public class Employee {

	private int empId;

	private String name;

	private String department;

	private int age;

	public Employee() {

	}

	public Employee(int empId, String name, String department, int age) {
		super();
		this.empId = empId;
		this.name = name;
		this.department = department;
		this.age = age;
	}

	public int getEmpId() {
		return empId;
	}

	public void setEmpId(int empId) {
		this.empId = empId;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getDepartment() {
		return department;
	}

	public void setDepartment(String department) {
		this.department = department;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return "Employee [empId=" + empId + ", name=" + name + ", department=" + department + ", age=" + age + "]";
	}

}

Till Java-7 if we have to sort a collection of Employee class mentioned above-using java.util.Comparator, we can achieve it in the following ways.

1. Using an anonymous class:

static void sortingListTheOldWay(){
	Collections.sort(employeeList,new Comparator<Employee>() {

		@Override
		public int compare(Employee e1, Employee e2) {
			
			return e1.getEmpId() - e2.getEmpId();
		}
		
	}); 
	
}

2. Using a Separator class:

class EmployeeDepartmentComparator implements Comparator<Employee>{

	@Override
	public int compare(Employee o1, Employee o2) {
		return o1.getDepartment().compareTo(o2.getDepartment());
	}
}

But after the arrival of Java-8, we can rewrite the first way like below using Lambda.

static void sortingUsingLambdaOneWay(){
	employeeList.sort((Employee e1,Employee e2) -> e1.getEmpId()-e2.getEmpId());
}

To make the above code simpler we can simplify the above expression by excluding the type definition. The compiler is capable of inferring these types of definitions on its own.

static void sortingUsingLambdaAnotherWay(){
	employeeList.sort((e1, e2) -> e1.getEmpId()-e2.getEmpId());
}

We can even sort a collection by defining a static method and then using the Static method reference. Refer the following code snippet.

static int compareByAge(Employee e1, Employee e2){
    return e1.getAge() - e2.getAge();
}

static void sortingUsingLambdaUsingStaticMethodReference(){
	employeeList.sort(ComparatorUsingLambda::compareByAge);
}

Refer the below complete code and uncomment the method call in main method one by to see the output of each method.

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class ComparatorUsingLambda {

	static List<Employee> employeeList;
	
	public static void main(String[] args) {
		
		loadData();
		
		System.out.println("Employee List before sorting "+employeeList);
		
		sortingListTheOldWay();
		//sortingUsingCustomComparatorClass();
		//sortingUsingLambdaOneWay();
		//sortingUsingLambdaSecondWay();
		//sortingUsingLambdaUsingStaticMethodReference();
		System.out.println("Employee List after sorting "+employeeList);
	}
	
	static void sortingListTheOldWay(){
		Collections.sort(employeeList,new Comparator<Employee>() {

			@Override
			public int compare(Employee e1, Employee e2) {
				
				return e1.getEmpId() - e2.getEmpId();
			}
			
		}); 
	}
	
	static void sortingUsingCustomComparatorClass(){
		Collections.sort(employeeList,new EmployeeDepartmentComparator());
	}

	static void sortingUsingLambdaOneWay(){
		employeeList.sort((Employee e1,Employee e2) -> e1.getEmpId()-e2.getEmpId());
	}
	
	static void sortingUsingLambdaSecondWay(){
		employeeList.sort((e1, e2) -> e1.getEmpId()-e2.getEmpId());
	}
	
	static void sortingUsingLambdaUsingStaticMethodReference(){
		employeeList.sort(ComparatorUsingLambda::compareByAge);
	}
	
	static int compareByAge(Employee e1, Employee e2){
		
		return e1.getAge() - e2.getAge();
	}
	
	
	static void loadData(){
		employeeList = Arrays.asList(
			new Employee(10002, "Employee 1", "IT", 34),
			new Employee(10001, "Employee 2", "IT", 26),
			new Employee(10003, "Employee 3", "Admin", 56),
			new Employee(10005, "Employee 4", "Sales", 32),
			new Employee(10004, "Employee 5", "IT", 23)
		);
	}
	
}

class EmployeeDepartmentComparator implements Comparator<Employee>{

	@Override
	public int compare(Employee o1, Employee o2) {
		return o1.getDepartment().compareTo(o2.getDepartment());
	}
}

happy Learning !!

Leave a Comment