1

Let's say I have two objects with property Customer which is object that has property ID. How would you compare those two object. I tried to write some common java if statement, but is long and really clumsy.

I tried something like this

new EqualsBuilder().append(o1.getCustomer(), o2.getCustomer())
            .append(o1.getCustomer().getId(), o2.getCustomer().getId()).isEquals()

but it fails if getCustomer of one object returns null(this is for cases the object is for anonymous customer, thus NullPointerException occurs). How can I write it in the most readable way. Can I somehow utilize java Optional??

UPDATE: Problem is I'm comparing uncomparable. O1 and o2 are different classes. In this case the primal flaw is that I cannot use EqualsBuilder at all.

Maybe I can use this, which is really not more readable then if statement.

Object1 o1 = ...;
Object2 o2 = ...;
boolean equals Optional.of(o1).map(VoucherDTO::getCustomer).map(CustomerDTO::getId).orElse(0L).equals(Optional.of(o1).map(VoucherDTO::getCustomer).map(CustomerDTO::getId).orElse(0L));
4

1 回答 1

2

下面的呢?我会让这两个客户只有在 id 相等的情况下才相等。

return o1.getCustomer() == null 
       ? o2.getCustomer() == null
       : o1.getCustomer().equals(o2.getCustomer())
                  &&  o1.getCustomer().getId() == o2.getCustomer().getId();
于 2017-02-08T14:44:28.240 回答