Alireza Noorali
Alireza Noorali

Reputation: 3265

Sorting List of Objects by long property

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?

Upvotes: 3

Views: 968

Answers (2)

Amit Bera
Amit Bera

Reputation: 7325

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 );
});

Upvotes: 2

Dinesh
Dinesh

Reputation: 1086

You can implement the compare method as follows. This should solve your problem.

public int compare(MyObject o1, MyObject o2) {
                return o1.getPrice() < o2.getPrice ?-1 :(o1.getPrice == o2.getPrice ?0 :1);

}

Upvotes: 1

Related Questions