Friday, September 16, 2016

Java 8 equals helper using lambda expression

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Equals {
 private Equals() {}
 
 public static <t> boolean of(Class<t> type, Object obj, Predicate<t> pred) {
  if (obj == null) {
   return false;
  }
  if (!type.isInstance(obj)) {
   return false;
  }
  T other = type.cast(obj);
  return pred.test(other);
 }
}
</t></t></t>
Usage example:
1
2
3
4
5
6
7
@Override
public boolean equals(Object obj) {
 return Equals.of(ClassKey.class, obj, other ->
   Objects.equals(this.kind, other.kind) &&
   Objects.equals(this.obj, other.obj)
  );
}