Enter your E-mail Address below for Free E-mail Alerts right Into your Inbox: -

Showing posts with label java comparator example. Show all posts
Showing posts with label java comparator example. Show all posts

Thursday

Java Comparator sample program example

Java Comparator sample program example

import java.util.Comparator;


public class Employee {

private String empName;
private String department;
private int age;
public Employee(String empName,String department,int age) {
this.empName = empName;
this.department = department;
this.age = age;
}

public static class OrderByName implements Comparator<Employee>
{

@Override
public int compare(Employee e1, Employee e2) {
// TODO Auto-generated method stub
return e1.empName.compareTo(e2.empName);
}

}

public static class OrderByDepartment implements Comparator<Employee>
{
@Override
public int compare(Employee e1, Employee e2) {
// TODO Auto-generated method stub
return e1.department.compareTo(e2.department);
}
}

public static class OrderByAge implements Comparator<Employee>
{
@Override
public int compare(Employee e1, Employee e2) {
// TODO Auto-generated method stub
return e1.age>e2.age?1:(e1.age<e2.age?-1:0);
}
}
/**
* @return the empName
*/
public String getEmpName() {
return empName;
}
/**
* @param empName the empName to set
*/
public void setEmpName(String empName) {
this.empName = empName;
}
/**
* @return the department
*/
public String getDepartment() {
return department;
}
/**
* @param department the department to set
*/
public void setDepartment(String department) {
this.department = department;
}
/**
* @return the age
*/
public int getAge() {
return age;
}
/**
* @param age the age to set
*/
public void setAge(int age) {
this.age = age;
}

}



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


public class Sample {

    public static void main(String args[])
    { 
   Employee e1 = new Employee("vaisakh","IT",21);
   Employee e2 = new Employee("rajkumar","EEE",22);
   Employee e3 = new Employee("binu","MECH",20);
   
   List<Employee> list = new ArrayList<Employee>();
   list.add(e1);
   list.add(e2);
   list.add(e3);

   Collections.sort(list, new Employee.OrderByName());
   System.out.println("Ordering based on name "+list);
   Collections.sort(list, new Employee.OrderByDepartment());
   System.out.println("Ordering based on department "+list);
   Collections.sort(list, new Employee.OrderByAge());
   System.out.println("Ordering based on age "+list);
    }
}