Search code examples
javaandroidsortingcollectionscustom-compare

Collections.sort does not change list


I have a list of games that I wish to sort by the number of scores they have (in descending order). I wrote this code for this purpose;

public void OnResponse(Object response) {
    List<Game> games = (List<Game>)response;
    Collections.sort(games, new Comparator<Game>() {
        @Override
        public int compare(Game o1, Game o2) {
            if( o1.scores.size() > o2.scores.size()) {
                return 1;
            } else {
                return 0;
            }
        }
    });
    trendingGames = games;
    gridView = view.findViewById(R.id.trendingGrid);
    gridView.setAdapter(new TrendingAdapter(games, getContext()));
    view.findViewById(R.id.progressBar).setVisibility(View.GONE);
}

However, when I check the debugger I see that the list does not change at all.


Solution

  • You could use Integer#compare to ease your life and make sure your Comparator contract is respected

    @Override
    public int compare(Game o1, Game o2) {
        int score1 = o1.scores.size();
        int score2 = o2.scores.size();
        return Integer.compare(score1, score2);
    }