Java Multi-Level Comparator

后端 未结 2 1216
别那么骄傲
别那么骄傲 2021-01-24 07:31

I am working on a problem where I must take these \"Song-artist pairs\" from an input file and sort alphabetically. The guidelines to the sorting goes like so:

  • Sh
2条回答
  •  春和景丽
    2021-01-24 08:02

    Let's say the class you said you managed to create is called SongArtistPair and it has a method called effectiveAuthor()which returns the author's name without the The, and a method getSongName() which returns the name of the song. You can use this pattern offered by the Java 8 Comparator API.

    Comparator comp = Comparator.comparing(SongArtistPair::effectiveAuthor).thenComparing(SongArtistPair::getSongName);
    

    After that, just use that comp as normal

    Check Comparator API docs for more cool stuff HERE

提交回复
热议问题