Java – a simpler way to reverse the comparator created inline by static methods (functional interfaces)?

Since the comparator < T > is a functional interface, I can do this

Comparator<Instant> instantComparator = Instant::compareTo;

I can change it now:

Comparator<Instant> instantComparatorReversed = instantComparator.reversed();

I can do this directly, but:

Comparator<Instant> cannotDoThis = (Instant::compareTo).reversed();

This makes sense, because instant:: CompareTo is only a method after all. In that case, it is The only way to say inline seems to be:

Comparator<Instant> instantComparatorReversedWithCast = ((Comparator<Instant>)Instant::compareTo).reversed();

also

Comparator.<Instant>reverSEOrder()

And as stated in the comments

Comparator.<Instant>naturalOrder().reversed()

The question now is: is there a shorter / more beautiful way to "inline" rather than that?

Solution

You can write a method that takes comparator as a parameter and invert it:

public static <T> Comparator<T> reverse(Comparator<T> comparator) {
    return comparator.reversed();
}

You might do this in a class full of utility methods and statically import the method

Then you can do this:

reverse(Instant:compareTo)
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>