Collection Sort using Comparable Interface


package com.orange.mail.controller;
public class Employee implements Comparable {

	private int emp_Id;
	private String emp_name;
	
	public Employee(int id, String name ) {
		super();
		this.emp_Id = id;
		this.emp_name = name;
	}
	
	public int compareTo(Object obj) {
		Employee employee = (Employee)obj;
		
		return (this.emp_Id < employee.emp_Id) ? -1 : (this.emp_Id > employee.emp_Id) ? 1 :0;
	}
	
	public int getEmp_Id() {
		return emp_Id;
	}
	public void setEmp_Id(int emp_Id) {
		this.emp_Id = emp_Id;
	}
	public String getEmp_name() {
		return emp_name;
	}
	public void setEmp_name(String emp_name) {
		this.emp_name = emp_name;
	}
	
}

package com.orange.mail.controller;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

public class EmployeeComparableSorting {
	public static void main(String[] args) {
		Employee employee1 = new Employee(1, "Rahul");
		Employee employee2 = new Employee(5, "Mehul");
		Employee employee3 = new Employee(3, "Manisha");
		Employee employee4 = new Employee(6, "Shahnahwaz");
		Employee employee5 = new Employee(2, "Hitesh");
		
		List<Employee> employees = new ArrayList<Employee>();
		employees.add(employee1);
		employees.add(employee2);
		employees.add(employee3);
		employees.add(employee4);
		employees.add(employee5);
		
	    System.out.println("Before Sorting");
	    for (Iterator iterator = employees.iterator(); iterator.hasNext();) {
			Employee employee = (Employee) iterator.next();
			System.out.println(employee.getEmp_Id() + ", "+employee.getEmp_name());
		}
		
	    System.out.println("After Sorting using Comparable");
	    Collections.sort(employees);
	    for (Iterator iterator = employees.iterator(); iterator.hasNext();) {
			Employee employee = (Employee) iterator.next();
			System.out.println(employee.getEmp_Id() + ", "+employee.getEmp_name());
		}	    
	}
}

Output:
Before Sorting
1, Rahul
5, Mehul
3, Manisha
6, Shahnahwaz
2, Hitesh
After Sorting
1, Rahul
2, Hitesh
3, Manisha
5, Mehul
6, Shahnahwaz