package com.bmchild.utils; import java.util.Objects; import java.util.function.Predicate; /** * Non functional way of chaining predicates together * @author brettchild * * @param */ public class PredicateChain { private T objectToTest; private Predicate predicate; public PredicateChain(T instanceToTest, Predicate predicate) { Objects.requireNonNull(instanceToTest); Objects.requireNonNull(predicate); this.objectToTest = instanceToTest; this.predicate = predicate; } /** * Private constructor to create new chains * @param predicate */ private PredicateChain(Predicate predicate) { Objects.requireNonNull(predicate); this.predicate = predicate; } public Predicate toPredicate() { return t -> this.test(); } public boolean test() { return predicate.test(objectToTest); } public PredicateChain and(PredicateChain other) { Objects.requireNonNull(other); return new PredicateChain(t -> this.test() && other.test()); } public PredicateChain or(PredicateChain other) { Objects.requireNonNull(other); return new PredicateChain(t -> this.test() || other.test()); } public PredicateChain negate() { return new PredicateChain(this.toPredicate().negate()); } }