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:
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;
}
}
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