Java Multi-Level Comparator

后端 未结 2 1213
别那么骄傲
别那么骄傲 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 07:55

    In your compare method, compare the song titles if the artists names are identical. Like this:

    public static class SongComparator implements Comparator<Song>{
        public int compare(Song a, Song b){
            int rslt a.effectiveAuthor().compareTo(b.effectiveAuthor());
            if (rslt ==0)
            {
                // compare song names
                rslt = a.getSongName().compareTo(b.getSongName());
            }
            return rslt;
        }
    }
    
    0 讨论(0)
  • 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<SongArtistPair> 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

    0 讨论(0)
提交回复
热议问题