Search code examples
sortingarraylisthashmapdescendant

Descending Sorting of an ArrayList of Object


I need to sort this ArrayObject :

public ArrayList<WPPost> posts;

on descending :

posts.get(i).getRating()

I have tried with HashMaps, LinkedHashMaps, I haven't found anything. What's the best solution ?


Solution

  • I think that one of the best solutions is the use of Collections.sort

        Collections.sort(posts, new Comparator<WPPost>() {
            @Override
            public int compare(WPPost o1, WPPost o2) {
                return o2.getRating() - o1.getRating();
            }
        });
    

    In some implemetations Collectios sort use merge sort algorithm, that will give you a O(log n) complexity.