Zib*_*eah 4 migration comparator java-7 java-8
我在理解如何在Java7中"迁移"一个简单的Comparator时遇到了麻烦.
我在Java8中使用的实际版本如下:
private static final Comparator<Entry> ENTRY_COMPARATOR = Comparator.comparing(new Function<Entry, EntryType>() {
@Override
public EntryType apply(Entry t) {
return t.type;
}
})
.thenComparing(Comparator.comparingLong(new ToLongFunction<Entry>() {
@Override
public long applyAsLong(Entry value) {
return value.count;
}
}).reversed());
Run Code Online (Sandbox Code Playgroud)
但在构建阶段我得到这个错误:
static interface method invocations are not supported in -source 7
Run Code Online (Sandbox Code Playgroud)
如何将相同的比较器迁移到Java7?我正在谷歌搜索和搜索解决方案,但我唯一能想到的是,将我自己的类实现为Comparator接口实现.
但是,如果我走这条路,我怎样才能在同一"比较"方法中应用"比较","然后比较"和"反向"?
提前致谢
甚至你的java-8版本也可以缩短,更容易阅读:
Comparator.comparing(Entry::getType)
.thenComparingLong(Entry::getCount)
.reversed();
Run Code Online (Sandbox Code Playgroud)
使用guava(java-7兼容),这看起来有点冗长:
@Override
public int compare(Entry left, Entry right) {
return ComparisonChain.start()
.compare(left.getType(), right.getCount(), Ordering.natural().reversed())
.compare(left.getCount(), right.getCount(), Ordering.natural().reversed())
.result();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
86 次 |
| 最近记录: |