Sort Arraylist of Custom Object in Android

Frequently used code samples and tutorials
vivekkalady
Site Admin
Posts: 35
Joined: Tue Nov 18, 2014 2:39 pm

Sort Arraylist of Custom Object in Android

Postby vivekkalady » Fri Nov 21, 2014 5:06 pm

Date Comparison

Since Date implements Comparable, it has a compareTo method just like String does.

So custom comparator could look like this:

Code: Select all

public class CustomComparator implements Comparator<MyObject> {
    @Override
    public int compare(MyObject o1, MyObject o2) {
        return o1.getStartDate().compareTo(o2.getStartDate());
    }
}


sorting code would be just about like you wrote:

Code: Select all

Collections.sort(arrlstData, new CustomComparator());



String Comparison


Code: Select all

Collections.sort(studList, new Comparator<Student>(){
    public int compare(Student s1, Student s2) {
        return s1.getFirstName().compareToIgnoreCase(s2.getFirstName());
    }
});



Integer Comparison

Code: Select all

List<Person> sortedByAgePersons = new ArrayList<Person>(persons);
Collections.sort(sortedByAgePersons, new Comparator<Person>() {
        public int compare(Person p1, Person p2) {
           return Integer.valueOf(p1.getAge()).compareTo(p2.getAge());
        }
});

Return to “Tutorials & Examples”

Who is online

Users browsing this forum: No registered users and 1 guest

cron