Sunday, November 19, 2017

Java 8 Comparator Example using Lambda Expressions


                             Lambda Expressions with  Comparator Example
  1. Main purpose of Comparator is to sort  a Collection of Objects which can be compared with each other.
  2. Comparison can be done using Comparable interface as well, but it restrict you compare these objects in a single particular way only.
  3. If you want sort this collection, based on multiple fields , then you  have to use Comparator only.
  4. I am sharing some knowledge about lambda expressions
    Demo with Employee with four attributes, will see various use cases:

    class Employee {
private Integer id;

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public Integer getAge() {
return age;
}

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

private String firstName;
private String lastName;
private Integer age;

public Employee(Integer id, String firstName, String lastName, Integer age)
 {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
 }

@Override
public String toString() 
{
return "\n[" + this.id + "," + this.firstName + "," + this.lastName + "," + this.age + "]";
}

@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof Employee)) {
return false;
}
Employee empObj = (Employee) obj;
return this.age == empObj.age && this.firstName.equalsIgnoreCase(empObj.firstName)
&& this.lastName.equalsIgnoreCase(empObj.lastName);
}

@Override
public int hashCode() {
int hash = 1;
hash = hash * 17 + this.firstName.hashCode();
hash = hash * 17 + this.lastName.hashCode();
hash = hash * 31 + this.age;
return hash;
}
}

class Employee {
private Integer id;

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public Integer getAge() {
return age;
}

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

private String firstName;
private String lastName;
private Integer age;

public Employee(Integer id, String firstName, String lastName, Integer age) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}

@Override
public String toString() {
return "\n[" + this.id + "," + this.firstName + "," + this.lastName + "," + this.age + "]";
}

@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof Employee)) {
return false;
}
Employee empObj = (Employee) obj;
return this.age == empObj.age && this.firstName.equalsIgnoreCase(empObj.firstName)
&& this.lastName.equalsIgnoreCase(empObj.lastName);
}

@Override
public int hashCode() {
int hash = 1;
hash = hash * 17 + this.firstName.hashCode();
hash = hash * 17 + this.lastName.hashCode();
hash = hash * 31 + this.age;
return hash;
}
}
Main Class:


package com.coding.core.sort;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class ComparatorWithLamda {

public static void main(String[] args) {
// TODO Auto-generated method stub

// 1) Sort all employees by first name
List<Employee> employees = getEmployees();

// Sort all employees by first name
employees.sort(Comparator.comparing(e -> e.getFirstName()));

// OR you can use below
employees.sort(Comparator.comparing(Employee::getFirstName));

System.out.println("*** sorted emps by First Name*********");
// Let's print the sorted list
System.out.println(employees);
System.out.println();

System.out.println("*******************************");
System.out.println("Sorted All emp's by Fname with reverse Order");
// Sort all employees by first name; And then reversed
Comparator<Employee> comparator = Comparator.comparing(e -> e.getFirstName());
employees.sort(comparator.reversed());

// Let's print the sorted list
System.out.println(employees);
System.out.println("*********************************");

}

private static List<Employee> getEmployees() {
List<Employee> employees = new ArrayList<>();
employees.add(new Employee(1, "Lokesh", "Gupta", 32));
employees.add(new Employee(2, "Rajesh", "Guru", 28));
employees.add(new Employee(3, "Avinash", "Rijesh", 52));
employees.add(new Employee(4, "Nirlam", "Tracy", 72));
employees.add(new Employee(5, "David", "Kameron", 19));
employees.add(new Employee(6, "Yashod", "kumar", 25));
employees.add(new Employee(7, "Karan", "Johar", 59));

return employees;
}
//Case3 :

/*4) Sort By first name and then by last name (sort on multiple fields)

Here we are sorting list of employees first by their first name, and then sort again the list of last name. Just as we apply sorting on SQL statements. It’s actually a very good feature.


Now you don’t need to always use sorting on multiple fields in SQL select statements, you can sort them in java as well.*/

// Sorting on multiple fields; Group by.
Comparator<Employee> groupByComparator = Comparator.comparing(Employee::getFirstName)
.thenComparing(Employee::getLastName);
employees.sort(groupByComparator);

System.out.println(employees);


}
Output:
***********Sorted All Employees by First Name*********
[
[3,Avinash,Rijesh,52], 
[5,David,Kameron,19], 
[7,Karan,Johar,59], 
[1,Lokesh,Gupta,32], 
[4,Nirlam,Tracy,72], 
[2,Rajesh,Guru,28], 
[6,Yashod,kumar,25]]

****************************************************
Sorted All Employees by First Name with reverse Order
[
[6,Yashod,kumar,25], 
[2,Rajesh,Guru,28], 
[4,Nirlam,Tracy,72], 
[1,Lokesh,Gupta,32], 
[7,Karan,Johar,59], 
[5,David,Kameron,19], 
[3,Avinash,Rijesh,52]]

*****************************************************




No comments:

Post a Comment

How to remove duplicate elements from an ArrayList in Java

How to remove duplicate elements from an ArrayList in Java. Ø   ArrayList allows adding duplicate elements, sometime there may be...