枚举使用lambda表达式覆盖方法

时间:2016-01-21 15:53:14

标签: lambda interface enums java-8 comparator

我有两个解决方案,想要一个构成比较器库的枚举:

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

和...

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());
        };
    };

}

如果我想替换期望Comparator的枚举值,在第一个解决方案中我必须说SongComparator.BY_TITLE.get();而在第二个解决方案中,我可以说SongComparator2.BY_TITLE。

第二种在这个意义上更好,但是,我不喜欢为每个枚举值编写public int compare ...等,而是希望在第一种方法中使用Comparator.comparing。有没有办法实现这个目标?

我几乎想说的是:BY_TITLE {return Comparator.comparing(Song :: getTitle); };

1 个答案:

答案 0 :(得分:5)

错误:

public enum SongComparator implements Comparator<Song> {

    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 int compare(Song s1, Song s2) {
        return comp.compare(s1, s2);
    };

}