Java 8 Lambda : Comparator example

Posted by

In this example, we will show you how to use Java 8 Lambda expression to write a Comparator to sort a List

package com.cankube.example.java8.monoexamples;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.junit.Test;

public class Java8Comparator {

	@Test
	public void withNonLambda() {
		System.out.println("Before Sort");
		List<Employee> employees = this.employees();
		for (Employee employee: employees) {
			System.out.println(employee);
		}

		Collections.sort(employees, new Comparator<Employee>() {
			@Override
			public int compare(Employee o1, Employee o2) {
				return o1.getAge() - o2.getAge();
			}
		});
		System.out.println("After Sort");
		for (Employee employee: employees) {
			System.out.println(employee);
		}
	}

	@Test
	public void withLambda() {
		System.out.println("Before Sort");
		List<Employee> employees = this.employees();
		for (Employee employee: employees) {
			System.out.println(employee);
		}

		Collections.sort(employees, Comparator.comparingInt(Employee::getAge));

		System.out.println("After Sort");
		for (Employee employee: employees) {
			System.out.println(employee);
		}
	}

	private List<Employee> employees() {
		List<Employee> lists = new ArrayList<>();
		lists.add(new Employee("robert", 40000, 40));
		lists.add(new Employee("jesica", 60000, 35));
		lists.add(new Employee("kathy", 80000, 50));
		lists.add(new Employee("rock", 50000, 20));
		return lists;
	}
	class Employee {
		private String name;
		private double salary;
		private int age;

		public Employee(String name, double salary, int age) {
			this.name = name;
			this.salary = salary;
			this.age = age;
		}

		public String getName() {
			return name;
		}

		public double getSalary() {
			return salary;
		}

		public int getAge() {
			return age;
		}

		@Override
		public String toString() {
			return "Employee{" +
				   "name='" + name + '\'' +
				   ", salary=" + salary +
				   ", age=" + age +
				   '}';
		}
	}

}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.