문제

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