Sunday, December 7, 2014

SortCollectionByComparator


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

public class SortCollectionByComparator {
   
   
public static void main(String[] args){
        List<Employee> empList = new ArrayList<Employee>();
        empList.add(new Employee("John",10));
        empList.add(new Employee("Alex",20));
        empList.add(new Employee("Mark",30));
       
        Collections.sort(empList,new SortEmpByNameComparator());
        for (Employee emp: empList){
            System.out.println(emp.getEmpName()+" "+emp.getEmpId());
        }
    }

}




public class Employee {
    private String empName;
    private Integer empId;

    public Employee() {
    }

    public String getEmpName() {
        return empName;
    }

    public void setEmpName(String empName) {
        this.empName = empName;
    }

    public Integer getEmpId() {
        return empId;
    }

    public void setEmpId(Integer empId) {
        this.empId = empId;
    }
   
    public Employee(String empName, Integer empId){
        super();
        this.setEmpName(empName);
        this.setEmpId(empId);
       
    }
}



import java.util.Comparator;

public class SortEmpByNameComparator implements Comparator<Employee> {

    @Override
    public int compare(Employee emp1, Employee emp2) {
        return emp1.getEmpName().compareTo(emp2.getEmpName());
    }

}

OUTPUT
Alex 20
John 10
Mark 30


No comments:

Post a Comment