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?

有帮助吗?

解决方案

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>.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top