Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use Guava's ComparisonChain to handle null fields in a special way?

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?

like image 474
Daniel Kaplan Avatar asked Jun 18 '13 22:06

Daniel Kaplan


1 Answers

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

like image 104
Eric Jablow Avatar answered Sep 29 '22 19:09

Eric Jablow