Sorting List of Objects by long property

Alireza Noorali :

It is possible to Compare int values using Collections.sort(object) 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 is available in API 19 and higher 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 the minSdkVersion of my app is 16 and my price values are bigger than the maximum of int range!!!

How can I sort the List of my objects by long property in API level 16 and higher?

Amit Bera :

Look at the definition of Long#compare :

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

Similary, you simply can return 1 if the value greater than the other value, 0 if equals and -1 if 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 );
});

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=125456&siteId=1