Friday, July 12, 2013

Comparator interface to sort java object based on it's parameter.

Sort list of Employee object based on it's name parameter.

1.Bean class:
package com.collection.javacodepractices;

public class Employee {
      private int rollNo;
      private String name;

      public int getRollNo() {
            return rollNo;
      }

      public void setRollNo(int rollNo) {
            this.rollNo = rollNo;
      }

      public String getName() {
            return name;
      }

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

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


}

2.Comparable class:
package com.collection.javacodepractices;

import java.util.Comparator;

public class EmployeeComparable implements Comparator<Employee>{

      @Override
      public int compare(Employee empOne, Employee empTwo) {
            return (empOne.getName().compareToIgnoreCase(empTwo.getName())<0?-1:                                                   (empOne.getName().equalsIgnoreCase(empTwo.getName())?0:1));
      }

}

3.Client class:
package com.collection.javacodepractices;

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

public class Client {
      public static void main(String args[]) {
            List<Employee> empList = new ArrayList<Employee>();

            // 1. employee setting.
            Employee emp1 = new Employee();
            emp1.setRollNo(1);
            emp1.setName("Bijoy");
            // 2. employee setting.
            Employee emp2 = new Employee();
            emp2.setRollNo(2);
            emp2.setName("Bappa");
            // 3. employee setting.
            Employee emp3 = new Employee();
            emp3.setRollNo(3);
            emp3.setName("Chintu");
            // 4. employee setting.
            Employee emp4 = new Employee();
            emp4.setRollNo(4);
            emp4.setName("Rahul");
            // 5. employee setting.
            Employee emp5 = new Employee();
            emp5.setRollNo(5);
            emp5.setName("Ajoy");
           
            //Add employee object to list.
            empList.add(emp1);
            empList.add(emp2);
            empList.add(emp3);
            empList.add(emp4);
            empList.add(emp5);
           
            //sorting employee based on name using comparator interface.
            Collections.sort(empList, new EmployeeComparable());
           
            //Print Employee object.
            for(Employee emp:empList){
                  System.out.println(emp.toString());
            }
      }
}

OUTPUT:
Employee [rollNo=5, name=Ajoy]
Employee [rollNo=2, name=Bappa]
Employee [rollNo=1, name=Bijoy]
Employee [rollNo=3, name=Chintu]
Employee [rollNo=4, name=Rahul]