Pages

Monday 7 May 2012

Sorting a List based on the a columnValue /property (BeanComparator)


 Sorting a List<Bean> based on the a columnValue /property (BeanComparator)
Hi  everyone,
            Here is code snippet for sorting a resultant List, which we obtain after performing our business logic .All we need to use is a class provided by apache i.e. org.apache.commons.beanutils.BeanComparator .
Its has a constructor  with a parameter  i.e. String PropertyName .Constructs a property-based comparator for beans. This compares two beans by the property specified in the property parameter. This constructor creates a BeanComparator that uses a ComparableComparator to compare the property values.
Passing "null" to this constructor will cause the BeanComparator to compare objects based on natural order,  that is java.lang.Comparable.


package com.sample.test.sorting;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.commons.beanutils.BeanComparator;
/**
 * @Author Srikanth Reddy
 * @Description SortingUtil provides All sorting  logic  to be used by  all the portlets.
 */
public class SortingUtil {
                public static final boolean DESC = true;   
                /**
                 * Sorts the given List based on columnName.
                 * @param inputList
                 * @param columnName
                 * @return
                 */
    @SuppressWarnings("rawtypes")
                public static List sort(List inputList, String columnName)
    {
            return sort(inputList, false, columnName);
    }
        /**
     * Sorts the given List based on columnName and order.
     * @param inputList
     * @param desc
     * @param columnName
     * @return
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
                public static List sort(List inputList, boolean desc, String columnName)
    {           
            List outputList = new ArrayList(inputList);
            BeanComparator comp = new BeanComparator(columnName);
            Collections.sort(outputList, comp);
            if (desc) {
                    Collections.reverse(outputList);
            }
            return outputList;
    }
}

To use it in your application ,just   call the above class and pass your list to be sorted and property on which it should be sorted.
Ie.
List sortedList = SortingUtil.sort(unsortedList, columnName);
And for Descending Order:
List sortedList = SortingUtil.sort(unsortedList,true, columnName);

Now that you know how to sort a List of  Object /Bean  based on one of the property/columName.
Lets see how to sort a List on multiple coloumNames/Properties  >
We use ComparatorChain.
Why we need ComparatorChain?
If  there is a need of multi-column sorting similar to SQL, then you can use this! The following example sorts the list using the firstName, SecondName and Division. If the firstName is same, then the sorting happens on SecondName and if the SecondName is also same, the sorting happens on Division.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Random;
import org.apache.commons.beanutils.BeanComparator;
import org.apache.commons.collections.comparators.ComparatorChain;
import org.apache.commons.collections.comparators.NullComparator;
public class ComparatorExample {
public static void main(String[] args) {
Random idRandomizer = new Random();
List studentList = new ArrayList();
StudentBean stBean1 = new StudentBean(idRandomizer.nextInt(), “Jagan”,
“Asokan”, “III”, “Bangalore”);
StudentBean stBean2 = new StudentBean(idRandomizer.nextInt(), “Jagan”,
“Asokan”, “II”, “Bangalore”);
StudentBean stBean3 = new StudentBean(idRandomizer.nextInt(), “Satya”,
“Asokan”, “III”, “Chennai”);
StudentBean stBean4 = new StudentBean(idRandomizer.nextInt(), “Balaji”,
“MK”, “I”, “Chennai”);
StudentBean stBean5 = new StudentBean(idRandomizer.nextInt(), “Satya”,
“Asokan”, “IV”, “Chennai”);
StudentBean stBean6 = new StudentBean(idRandomizer.nextInt(), “Balaji”,
“MK”, “V”, “Chennai”);
StudentBean stBean7 = new StudentBean(idRandomizer.nextInt(), “Jagan”,
“Asokan”, “VI”, “Chennai”);
StudentBean stBean8 = new StudentBean(idRandomizer.nextInt(), “Venu”,
“Karthik”, “I”, “Bangalore”);
studentList.add(stBean1);
studentList.add(stBean2);
studentList.add(stBean3);
studentList.add(stBean4);
studentList.add(stBean5);
studentList.add(stBean6);
studentList.add(stBean7);
studentList.add(stBean8);

Comparator<StudentBean> firstNameComparator = new BeanComparator(
“firstName”, new NullComparator(true));
Comparator<StudentBean> secondNameComparator = new BeanComparator(
“secondName”, new NullComparator(true));
Comparator<StudentBean> divisionComparator = new BeanComparator(
“division”, new NullComparator(true));
ComparatorChain studentChain = new ComparatorChain();
studentChain.addComparator(firstNameComparator);
studentChain.addComparator(secondNameComparator);
studentChain.addComparator(divisionComparator);

System.out.println(“BEFORE”);
for (int i = 0; i < studentList.size(); i++) {
System.out.println(studentList.get(i));
}
Collections.sort(studentList, studentChain);
System.out.println(“AFTER”);
for (int i = 0; i < studentList.size(); i++) {
System.out.println(studentList.get(i));
}
}
}
The Bean Class
public class StudentBean {
private int rollNumber;
private String firstName;
private String secondName;
private String division;
private String address;
@Override
public String toString() {
return “StudentBean [rollNumber=" + rollNumber + ", firstName="
+ firstName + ", secondName=" + secondName + ", division="
+ division + ", address=" + address + "]“;
}
public StudentBean(int rollNumber, String firstName, String secondName,
String division, String address) {
super();
this.rollNumber = rollNumber;
this.firstName = firstName;
this.secondName = secondName;
this.division = division;
this.address = address;
}
public int getRollNumber() {
return rollNumber;
}
public void setRollNumber(int rollNumber) {
this.rollNumber = rollNumber;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getSecondName() {
return secondName;
}
public void setSecondName(String secondName) {
this.secondName = secondName;
}
public String getDivision() {
return division;
}
public void setDivision(String division) {
this.division = division;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
The result
BEFORE
StudentBean [rollNumber=1612364660, firstName=Jagan, secondName=Asokan, division=III, address=Bangalore]
StudentBean [rollNumber=724494682, firstName=Jagan, secondName=Asokan, division=II, address=Bangalore]
StudentBean [rollNumber=-861754848, firstName=Satya, secondName=Asokan, division=III, address=Chennai]
StudentBean [rollNumber=588244880, firstName=Balaji, secondName=MK, division=I, address=Chennai]
StudentBean [rollNumber=-1459805186, firstName=Satya, secondName=Asokan, division=IV, address=Chennai]
StudentBean [rollNumber=1559882159, firstName=Balaji, secondName=MK, division=V, address=Chennai]
StudentBean [rollNumber=762774394, firstName=Jagan, secondName=Asokan, division=VI, address=Chennai]
StudentBean [rollNumber=1545447361, firstName=Venu, secondName=Karthik, division=I, address=Bangalore]

AFTER
StudentBean [rollNumber=588244880, firstName=Balaji, secondName=MK, division=I, address=Chennai]
StudentBean [rollNumber=1559882159, firstName=Balaji, secondName=MK, division=V, address=Chennai]
StudentBean [rollNumber=724494682, firstName=Jagan, secondName=Asokan, division=II, address=Bangalore]
StudentBean [rollNumber=1612364660, firstName=Jagan, secondName=Asokan, division=III, address=Bangalore]
StudentBean [rollNumber=762774394, firstName=Jagan, secondName=Asokan, division=VI, address=Chennai]
StudentBean [rollNumber=-861754848, firstName=Satya, secondName=Asokan, division=III, address=Chennai]
StudentBean [rollNumber=-1459805186, firstName=Satya, secondName=Asokan, division=IV, address=Chennai]
StudentBean [rollNumber=1545447361, firstName=Venu, secondName=Karthik, division=I, address=Bangalore]


Note :
My sorting logic based on the BeanComparator.
    Comparator<T> firstNameComparator = new BeanComparator(“firstName”, new NullComparator(true));
    Collections.sort(employeeList, firstNameComparator );

But why we need NullComparator?
If the values can be null, then the BeanComparator would thrown NullPointerException.

Hope this will help you …
Thanks & Regards
Srikanth S

2 comments: