Android-java- How to sort a list of objects by a certain value within the object

James andresakis picture James andresakis · Feb 2, 2012 · Viewed 207.4k times · Source

Im trying to sort through an arraylist of objects by a particular value within the object. What would be the best approach to do such a thing. Should I use Collections.sort() with some kind of comparator?

Im trying to sort a list of objects by a float value they hold in one of the variables.

EDIT: This is what I have so far:

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

the error states: Cannot invoke compareTo(double) on the primitive type double.

Is it because a comparator cant return anything other than a certain type?

Answer

Atif Mahmood picture Atif Mahmood · Dec 11, 2012

Follow this code to sort any ArrayList

Collections.sort(myList, new Comparator<EmployeeClass>(){
    public int compare(EmployeeClass obj1, EmployeeClass obj2) {
        // ## Ascending order
        return obj1.firstName.compareToIgnoreCase(obj2.firstName); // To compare string values
        // return Integer.valueOf(obj1.empId).compareTo(Integer.valueOf(obj2.empId)); // To compare integer values

        // ## Descending order
        // return obj2.firstName.compareToIgnoreCase(obj1.firstName); // To compare string values
        // return Integer.valueOf(obj2.empId).compareTo(Integer.valueOf(obj1.empId)); // To compare integer values
        }
    });