Suppose I have two objects and I want to know if a specific property is equal (nulls are managed exactly as I want):
// pre java 8
public static boolean equalsProp(SomeObject a, SomeObject b)
{
Object aProp = a != null ? a.getProp() : null;
Object bProp = b != null ? b.getProp() : null;
return (aProp == bProp) || (aProp != null && aProp.equals(bProp));
}
now that I have java 8, I can rewrite it to be generic:
public static <T, U> boolean equals(T a, T b, Function<? super T, ? extends U> mapper)
{
Object aProp = Optional.ofNullable(a).map(mapper).orElse(null);
Object bProp = Optional.ofNullable(b).map(mapper).orElse(null);
return (aProp == bProp) || (aProp != null && aProp.equals(bProp));
}
But I don't like to define a method like this in one of my classes.
Is there a java.lang.something.SomeJreBundledClass.equals(a, b, func)
that does exactly this?
Is there a best practice on how to do this (possibly without an utility method)?
Maybe it's not clear what I'm asking, I'll try again.
I have this piece of code:
Table t1 = ...
Table t2 = ...
if(!my.package.utils.ObjectUtils.equals(t1, t2, Table::getPrimaryKey))
{
// ok, these tables have different primary keys
}
I'm asking if:
- There's a JRE class that does the work of
my.package.utils.ObjectUtils
- There's a better, short and null-tolerant way to compare
t1.primaryKey
andt2.primaryKey
without writing an utility method.