I have two solutions to an idea of having an enum that forms a library of comparators:
public enum SongComparator {
BY_TITLE(Comparator.comparing(Song::getTitle)),
BY_ARTIST(Comparator.comparing(Song::getArtist)),
BY_DURATION(Comparator.comparing(Song::getDuration));
private Comparator<Song> comp;
private SongComparator(Comparator<Song> comp) {
this.comp = comp;
}
public Comparator<Song> get() {
return comp;
}
}
and...
public enum SongComparator2 implements Comparator<Song> {
BY_TITLE {
public int compare(Song s1, Song s2) {
return s1.getTitle().compareTo(s2.getTitle());
};
},
BY_ARTIST {
public int compare(Song s1, Song s2) {
return s1.getArtist().compareTo(s2.getArtist());
};
},
BY_DURATION {
public int compare(Song s1, Song s2) {
return Integer.compare(s1.getDuration(), s2.getDuration());
};
};
}
If I want to substitute an enum value where a Comparator is expected, in the first solution I have to say SongComparator.BY_TITLE.get(); whereas in the second solution I can just say SongComparator2.BY_TITLE.
The second is better in this sense, however, I don't like having to write public int compare... etc for each enum value and wanted instead to make use of Comparator.comparing as in the first approach. Is there a way to achieve this?
I almost wanted to say something like: BY_TITLE { return Comparator.comparing(Song::getTitle); };