Thursday, November 5, 2015

How to sort values in a java Class based on a property

Implement the Comparator class, say you have created a class called YourClass as follows

YourClass{
int age;
String name;
}
Supposing your requirement is to sort this Object based on the age then create a comparator as follows


public class YourComparator implements Comparator {

    YourClass yourList;

    public YourComparator (YourClass yourList) {
        super();
        this.yourList= yourList;
    }

    public int compare(Object o1, Object o2) {
        return compare((YourClass )o1, (YourClass )o2);
    }

    public int compare(YourClass o1, YourClass o2) {
        int age1= o1.getAge();
        int age2= o2.getAge();
        return (age1- age2);
    }
}

Then use this class to sort YourClass as follows, here i have a list input from the taskflow and then i am sorting this list and assigning back to the pageFlowScope.

    public void AgeSort() {
        List<YourClass > list = (List<YourClass >)resolveExpression("#{pageFlowScope.YourDetails}");
        YourClass  y1 = new YourClass ();
        YourComparator comp= new YourComparator (y1);
        Collections.sort(list, comp);  
        AdfFacesContext.getCurrentInstance().getPageFlowScope().put("YourDetails", list);
    }


No comments:

Post a Comment