Wednesday, September 19, 2012

Comparable and Comparator in Java


Employee record with Department, Emp Name and Emp Id:

Original Data:

BI :Kondal :109
HANA :Ban :103
HANA :Anand :115
ERP :Can :102
CRM :Yangi :100
BI :Damn :114

Required Format: Display the emp names in sorted way based on the department name.

BI :Damn :114
BI :Kondal :109
CRM :Yangi :100
ERP :Can :102
HANA :Anand :115
HANA :Ban :103

We can acheive this in two different ways.
1.  By implementing comparable interface in Employee class.
 - Override compareTo method
 - Invoke Collections.sort(arraylist);

2. By implementing comparator interface, as specified below without even touching the employee class
- Override compare method
- Invoke Collections.sort(arraylist, new EmployeeComparator());

Employee class

public
class Employee /* implements Comparable<Employee>*/ {
private int empId;
private String empName;
private String department;

public Employee(int empId, String empName, String department) {
this.empId = empId;
this.empName = empName;
this.department = department;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public int getEmpId() {
return empId;
}
public String getEmpName() {
return empName;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
/* @Override
public int compareTo(Employee o) {
if (this.getDepartment().compareTo(o.getDepartment()) == 0) {
return this.getEmpName().compareTo(o.getEmpName());
}
return this.getDepartment().compareTo(o.getDepartment());
}*/
}
 
EmployeeComparator class

import
java.util.Comparator;
 
public
class EmployeeComparator implements Comparator<Employee>{
@Override
public
int compare(Employee e1, Employee e2) {
if
(e1.getDepartment().compareTo(e2.getDepartment()) == 0) {
return
e1.getEmpName().compareTo(e2.getEmpName());
}
return
e1.getDepartment().compareTo(e2.getDepartment());
}
}

EmployeProfiles class

import
java.util.ArrayList;
import
java.util.Collections;

public
class EmployeProfiles {
public
static void main(String[] args) {
ArrayList<Employee> empList = new
ArrayList<Employee>();
empList.add(new
Employee(109, "Kondal", "BI"));
empList.add(new
Employee(103, "Ban", "HANA"));
empList.add(new
Employee(115, "Anand", "HANA"));
empList.add(new
Employee(102, "Can", "ERP"));
empList.add(new
Employee(100, "Yangi", "CRM"));
empList.add(new
Employee(114, "Damn", "BI"));
// Natural order in the array list
for
(Employee employee : empList) {
System.out
.println(employee.getDepartment() + " :"
+ employee.getEmpName() + " :" + employee.getEmpId());
}
// Apply sorting
Collections.sort(empList, new
EmployeeComparator());
System.out
.println("------------");
// sorted list
for
(Employee employee : empList) {
System.out
.println(employee.getDepartment() + " :"
+ employee.getEmpName() + " :" + employee.getEmpId());
}
}
}

No comments:

Post a Comment