Search My Blog

Monday, November 28, 2011

using Comparator to sort a List in JAVA

Sorting a List based on one of its attributes is achieved by using the Comparator interface.

For example,

public class EmpSortByName implements Comparator{

public int compare(Employee o1, Employee o2) {
return o1.getName().compareTo(o2.getName());
}
}

import java.util.*;

public class TestEmployeeSort {

public static void main(String[] args) {

List coll = Util.getEmployees();
//Collections.sort(coll);
//use Comparator implementation
Collections.sort(coll, new EmpSortByName());
printList(coll);
}

private static void printList(List list) {
System.out.println("EmpId\tName\tAge");
for (Employee e: list) {
System.out.println(e.getEmpId() + "\t" + e.getName() + "\t" + e.getAge());
}
}
}

This sorts the list based of employee names.

No comments:

Post a Comment