Skip to content Skip to sidebar Skip to footer

How To Sort Listview Items In Descending Order

So I have a listview where I wanted to sort the NumberOfRecords in descending order. I have a custom array adapter but I called my sorting class before I place a data in my ArrayLi

Solution 1:

You can use the following code to sort your integer list is descending order.Here we are overriding compare() so that it sorts in descending order.

//sort list in desc order 
            Collections.sort(myIntegerList, new Comparator<Integer>() {
                publicint compare(Integer one, Integer other) {
                     if (one >= other) {
                         return -1;
                     } else {
                         return1;
                     } 
                   }
            });

Hope it helps.

Solution 2:

Try with this Comparator.

Comparator objComparator = new Comparator() {
    publicint compare(Object o1, Object o2) {
        int no1 = Integer.parseInt((String) o1);
        int no2 = Integer.parseInt((String) o2);
        return  no1 < no2 ? -1 : no1 == no2 ? 0 : 1;
    }
};
Collections.sort(myIntegerList, objComparator);

Solution 3:

Okay, so I solved this by replacing the:

p2.getNumberOfRecords().compareTo(p1.getNumberOfRecords())

to:

(int) Integer.parseInt(p2.getNumberOfRecords()) - Integer.parseInt(p1.getNumberOfRecords())

So the simple compare of an integer in a String data type would not result correctly but to parse the string first by:

Integer.parseInt(string)

and get the true value of the number string.

Post a Comment for "How To Sort Listview Items In Descending Order"