Java8到Java7-迁移比较器

时间:2018-12-18 13:16:11

标签: java-8 migration java-7 comparator

我很难理解如何在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());

但是在构建阶段,我会收到此错误:

static interface method invocations are not supported in -source 7

如何将相同的比较器迁移到Java7?我正在搜索并寻找解决方案,但我唯一能想到的就是将自己的类实现为Comparator接口实现。

但是,如果我走这条路,我该如何在同一“比较”方法中同时应用“比较”,“然后比较”和“反向”?

预先感谢

3 个答案:

答案 0 :(得分:6)

即使使用以下方法,您的Java-8版本也可以变得更短,更容易阅读:

Comparator.comparing(Entry::getType)
          .thenComparingLong(Entry::getCount)
          .reversed();

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

答案 1 :(得分:3)

您可以使用单个compare方法编写逻辑:

public int compare (Entry one,Entry two) {
    int result = two.getType().compareTo(one.getType());
    if (result == 0) {
        result = Long.compare(two.getCount(),one.getCount());
    }
    return result;
}

请注意,通过交换比较的Entry实例的顺序来实现相反的顺序。

答案 2 :(得分:1)

您可以以Java 7的方式构造Comparator<Entry>,此后,您可以像在Java 8中那样链接默认方法,但是不使用lambda表达式或方法引用作为参数:

private static final Comparator<Entry> ENTRY_COMPARATOR = new Comparator<Entry>() {
    @Override
    public int compare(Entry left, Entry right) {
        return left.type.compareTo(right.type);
    }
}
.thenComparingLong(new ToLongFunction<Entry>() {
    @Override
    public long applyAsLong(Entry entry) {
        return entry.value;
    }
})
.reversed();

上面的代码是用-source 1.7编译的。