3

Is there a way to implement Ordering.lexicographical() with Java 8 Comparator?

Comparator.thenCompare seems to be limited in this

Kelvin Ng
  • 174
  • 1
  • 12
  • 4
    Yup, see the javadoc: http://google.github.io/guava/releases/snapshot/api/docs/com/google/common/collect/Ordering.html#lexicographical-- "Java 8 users: Use Comparators.lexicographical(Comparator) instead." –  Apr 28 '17 at 15:15

1 Answers1

9

Seemingly not, no.

As a result, Guava still provides this functionality, but in the new class Comparators: https://guava.dev/releases/snapshot/api/docs/com/google/common/collect/Comparators.html#lexicographical(java.util.Comparator).

Note that Guava generally does a good job telling you whether and how to migrate off of it to new Java features, so you're often better off checking its Javadoc than digging on your own. In this case: https://guava.dev/releases/snapshot/api/docs/com/google/common/collect/Ordering.html#lexicographical().

ruakh
  • 175,680
  • 26
  • 273
  • 307
  • 1
    To be clear, it should be stated that in this case Guava warns just against usage of `Ordering` class (which was undoubtedly nifty in pre-Java8 times). Unlike `Ordering.natural`, `nullsFirst` etc., which have full equivalent in Java8, there is unfortunately no full replacement for `Ordering.lexicographical` in Java8. For those who want not to use Guava in their project the "Java 8 users:"-section in Guava Javadoc is little bit misleading in this case, hence creating own implementation is unavoidable here. – Tomáš Záluský Sep 30 '21 at 08:18