Sorting an ArrayList of objects.
Posted by Albin Joseph | Posted in Java | Posted on 16-10-2008
8
Sorting an ArrayList of objects.
How do we sort an ArrayList of objects? The easiest way to sort an ArrayList of Objects is to use the Collections.sort() method. But how does the sort method know based on which field you need to sort? The solution is to implement the Comparator interface and override the compare method. For e.g.: if I have a class named person with the following structure.
class Person { private String firstName; private String lastName; public Person(){ } public Person(String firstName, String lastName){ this.firstName = firstName; this.lastName = lastName; } /** * @return Returns the firstName. */ public String getFirstName() { return firstName; } /** * @param firstName The firstName to set. */ public void setFirstName(String firstName) { this.firstName = firstName; } /** * @return Returns the lastName. */ public String getLastName() { return lastName; } /** * @param lastName The lastName to set. */ public void setLastName(String lastName) { this.lastName = lastName; } public String toString(){ return "## Firstname : "+this.firstName+", Lastname : "+this.lastName; } }
I have created some objects of Person class and they are added to an ArrayList. Now I need to sort the ArrayList based on Person’s firstName. The complete code listing for sorting the ArrayList is given below.
Person p = new Person("Bruce", "Willis"); Person p1 = new Person("Tom", "Hanks"); Person p2 = new Person("Nicolas","Cage"); Person p3 = new Person("John","Travolta"); ArrayList list = new ArrayList(); list.add(p); list.add(p1); list.add(p2); list.add(p3); Collections.sort(list, new Comparator(){ public int compare(Object o1, Object o2) { Person p1 = (Person) o1; Person p2 = (Person) o2; return p1.getFirstName().compareToIgnoreCase(p2.getFirstName()); } }); System.out.println(list);
Here inside my Collections.sort method I am implementing the Comparator interface and overriding the compare method.


Thanks.
Thanks alot for this. You saved me ALOT of time.
Cheers,
NJ
Very helpful!
Thanks.
Wonderful!
Thanks!
Thanks Albin!!
Thank you!
Great!
In this code, you have applied sorting based on firstName attribute only. How do you sort for two or more attributes. say either firstName or LastName or id?