简体   繁体   中英

Java predicate chaining with nested object

private static final Predicate<Parent> HAS_SON = parent -> IS_CHILD(parent.getChild);
private static final Predicate<Child> IS_CHILD = Objects::nonNull;
private static final Predicate<Parent> IS_PARENT = Objects::nonNull;
private static final Predicate<Parent> IS_FATHER = IS_PARENT.and(HAS_SON);

I am trying to chain predicates, with one twist, and that is at one of predicate I want to use child object.

This is hypothetical situation I tried to make things easier for understanding.

  1. Call will be made to is_father ( parent )
  2. is_father will check if parent is not null
  3. and() has_son
  4. has_son will call is_child (parent.getChild())
  5. is_child will check if child is not null

There is a problem HAS_SON, I know syntax is not right, and may be nesting(parent.child) might not be allowed. Can some one please confirm? right now work around I am using is

private static final Predicate<Parent> HAS_SON = parent -> parent.getChild() != null;

Do not forget that a Predicate is triggered by using the test method of the FunctionalInterface . The following will work

private static final Predicate<Child> IS_CHILD = Objects::nonNull;
private static final Predicate<Parent> HAS_SON = parent -> IS_CHILD.test(parent.getChild);
private static final Predicate<Parent> IS_PARENT = Objects::nonNull;
private static final Predicate<Parent> IS_FATHER = IS_PARENT.and(HAS_SON);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM