Java Comparator using .reverseOrder() but with an inner class

后端 未结 4 1711
借酒劲吻你
借酒劲吻你 2021-02-05 03:42

I am creating a simple program to learn about the Java Comparator class. I have sorted an Arraylist into order but now I want to sort the list in descending order b

4条回答
  •  生来不讨喜
    2021-02-05 04:19

    ArtistCompare artistCompare = new ArtistCompare();
    Collections.sort(songList, Collections.reverseOrder(artistCompare));
    

    Edit July 2015

    As this answer still gets some attention, here a small update:

    With Java SE 8 it's becoming easier to create a reversed comparator:

    Comparator songRatingComparator = Comparator.comparing(Song::getRating);
    Collections.sort(songList, songRatingComparator.reversed());
    

    And you can, of course, also use the Streams framework:

    List sortedSongList = songList.stream()
    .sorted(Comparator.comparing(Song::getRating).reversed())
    .collect(Collectors.toList());
    

提交回复
热议问题