Sorting the ArrayList or any Collection which has the primitive is easy. You can simply use the Sort method in Collection but thats not the case in real world situation you may be required to sort the objects based on the certain criteria. So first lets see how to sort the primitives.
import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class SortPrimitiesOfList { public static void main(String args[]) { List l = new ArrayList(); l.add("B"); l.add("A"); l.add("C"); l.add("E"); l.add("D"); Collections.sort(l); System.out.println(l); } }
Once you run the above code you will get the output as [A, B, C, D, E]
In order to sort the List of objects we need to implement either Comparable or Comparator interface. In this tutorial you will learn how to use the Comparator interface. This has a method called compare which lets you search between objects based on its properties.
import java.util.Collections; import java.util.Comparator; import java.util.List; public class SortObjectOfList { public static void main(String args[]) { List l = new ArrayList(); l.add(new Employee(20, "javainterviewpoint")); l.add(new Employee(10, "javainterview")); l.add(new Employee(30, "jip")); Collections.sort(l, new ComparatorImpl()); System.out.println(l); } } class ComparatorImpl implements Comparator { public int compare(Employee e1, Employee e2) { // if e1's id is greater than e2's eid then it returns a positive interger // if e1's id is lesser than e2's eid then it returns a negative interger // if e1's id is equal than e2's eid then it returns zero return (e1.getEid() - e2.getEid()); } } class Employee { private String empname; private int eid; public Employee(int eid, String empname) { this.eid = eid; this.empname = empname; } public String getEmpname() { return empname; } public void setEmpname(String empname) { this.empname = empname; } public int getEid() { return eid; } public void setEid(int eid) { this.eid = eid; } public String toString() { return " \n id : " + this.eid + " empname : " + this.empname; } }
on execution of the above you will get the output as
[ id : 10 empname : javainterview,
id : 20 empname : javainterviewpoint,
id : 30 empname : jip]
This compared the eid of e1 and e2 and got you the output in the ascending order , if you wish to sort in the descending order simply change the return statement in the compare method from return (e1.getEid() – e2.getEid()) to return (e2.getEid() – e1.getEid()).
Leave a Reply