Sort ArrayList Of Object

Sort ArrayList Of Object Example describes about How to sort an ArrayList of objects.

How to Sort An ArrayList Of Objects Using Comparator Interface

The best way to sort an ArrayList of Objects is using Collections.sort() method of Collections utility class.

But if you need to sort according to a particular field / column / property, then we can use Comparator interface and override compare method of Comparator interface.

Consider an ArrayList consists with lot of student objects, where student object have 2 properties like firstName & lastName. And you need to sort according to the firstName, then you can use comparator interface for sorting the ArrayList

int compare(T o1, T o2) Compares its two arguments for order.

Sort ArrayList Of Object

On the following example I am creating some student object and sorting according to their firstName

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class SortArrayListObject{
 
public static void main(String args[]){
   
Student s1  = new Student("Zerone","sonia");
    Student s2 =
new Student("Rockey", "CA");

        ArrayList<Student> studList =
new ArrayList<Student>();
        studList.add
(s1);
        studList.add
(s2);
       
        System.out.println
("before sorting %%%%%%%% "+studList);
       
        Collections.sort
(studList, new Comparator<Student>(){
            
public int compare(Student s1, Student s2) {
              
return s1.getFirstName().compareToIgnoreCase(s2.getFirstName());
           
}
        })
;

        System.out.println
("after  sorting %%%%%%%% "+studList);
 
}
}



// class Student

class Student {
 
private String firstName;
 
private String lastName;

 
public Student() {
  }

 
public Student(String firstName, String lastName) {
   
this.firstName = firstName;
   
this.lastName = lastName;
 
}
 
 
public String getFirstName() {
   
return firstName;
 
}

 
public void setFirstName(String firstName) {
   
this.firstName = firstName;
 
}

 
public String getLastName() {
   
return lastName;
 
}

 
public void setLastName(String lastName) {
   
this.lastName = lastName;
 
}

 
public String toString() {
   
return "Firstname : " + this.firstName + ", Lastname : "
       
+ this.lastName;
 
}
}
Output
before sorting %%%%%%%% [Firstname : Zerone, Lastname : sonia, Firstname : Rockey, Lastname : CA]
after sorting %%%%%%%% [Firstname : Rockey, Lastname : CA, Firstname : Zerone, Lastname : sonia]










2 Responses to "Sort ArrayList Of Object"
  1. JDH 2011-12-18 08:21:07.0
  1. admin 2011-12-18 08:21:07.0

Your email address will not be published. Required fields are marked *