Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java8 to Java7 - Migrate Comparators

I'm having troubles understanding how to "migrate" a simple Comparator in Java7.

The actual version I'm using in Java8 is like:

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

But in build phase I get this error:

static interface method invocations are not supported in -source 7

How can I migrate the same comparator to Java7? I'm googling and searching for solution but the only thing I can think of, is to implement my own class as a Comparator interface implementation.

But If I go down that road, how can I apply both "comparing", "then comparing" and "reverse" in the same "compare" method?

Thanks in advance

like image 343
Ziba Leah Avatar asked Dec 23 '22 02:12

Ziba Leah


1 Answers

Even your java-8 version can be made a lot shorter and easier to read with:

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

With guava (java-7 compatible), this looks a bit more verbose:

    @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();
    }
like image 126
Eugene Avatar answered Feb 23 '23 13:02

Eugene