Java – Sorts the list of objects by long properties

Sorts the list of objects by long properties… here is a solution to the problem.

Sorts the list of objects by long properties

You can use Collections.sort(object) to compare int values like this:

Collections.sort(priceList, new Comparator<MyObject>() {
    @Override
    public int compare(MyObject o1, MyObject o2) {
        return Integer.parseInt(o1.getPrice()) - Integer.parseInt(o2.getPrice());
    }
});

and

Long.compare are available in API 19 and later to compare long values using Collections.sort(object):

Collections.sort(priceList, new Comparator<MyObject>() {
    @Override
    public int compare(MyObject o1, MyObject o2) {
        return Long.compare(o2.getPrice(), o1.getPrice());
    }
});

But my application’s minSdkVersion is 16 and my price value is greater than the maximum value of the int range !!!

How do I sort my list of objects by long property at API level 16 and higher?

Solution

See Long#compare's definition:

public static int compare(long x, long y) {
    return (x < y) ? -1 : ((x == y) ? 0 : 1);
}

Similarly, you can return 1 if the value is greater than another value, 0 if equal to it, and -1 if it is less than:

Collections.sort(priceList, new Comparator<MyObject>() {
    @Override
    public int compare(MyObject o1, MyObject o2) {
       return (o1.getPrice() < o2.getPrice()) ? -1 : ((o1.getPrice() == o2.getPrice()) ? 0 :1 );
});

Related Problems and Solutions