Question

I have a ComplexObject with multiple fields and I want to say this:

  • if field x exists on both, move on to the next compare in the comparison chain.
  • if both are null, move on to the next compare in the comparison chain.
  • if one is null and the other is not, put nulls last

I'm not sure how to do this, because as far as I can tell

.compare(c1.getX(), c2.getX(), Ordering.arbitrary().nullsLast())

will

  1. consider the objects to be equal if they both exist and are equal
  2. consider the objects to be equal if they're both null.

Is there a way I can use Guava's ComparisonChain or Ordering class to achieve what I want? Or is there a better way to think about solving this problem?

Was it helpful?

Solution

Given your answer to my comment, just do a boolean comparison.

.compare(c1.getX() == null, c2.getX() == null)

And given your revised reply, if your class has a method

public XType getX() {...}

then consider making XType implement Comparable<XType> or providing a Comparator<XType>.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top