emmaJ
emmaJ

Reputation: 21

Return lazy evaluation of list of boolean statements , with any of it true

I have a series of boolean decision, each having a different condition to evaluate. If any of it evaluates to true it should return. Problem is, I do not want them to be eagerly evaluated. I have two implementations here, the first one works, but i have 10 such decisions to make so i want to get them all as a list, as soon as I put them into list/stream it evaluates all the decisions and fails the purpose. What I want is, if any of the condition evaluates to true it should stop right there and return, rest of the conditions should not get executed.

BooleanSupplier a = () -> compute("bb");
BooleanSupplier b = () -> computeSecond("aa");

// this works
System.out.println("Lazy match => " + lazyMatch(a, b));

// this doesn't
System.out.println("Lazy match list => " + lazyMatchList(Stream.of(a,b)));

static boolean lazyMatch(BooleanSupplier a, BooleanSupplier b) {
        return a.getAsBoolean() || b.getAsBoolean();
}

static boolean lazyMatchList(Stream<BooleanSupplier> lazyBooleanList) {
        return  lazyBooleanList.anyMatch(BooleanSupplier::getAsBoolean);
}

static boolean compute(String str) {
        System.out.println("executing...");
        return str.contains("ac");
}

// compute2 is something similar to compute

Upvotes: 1

Views: 404

Answers (1)

Bohemian
Bohemian

Reputation: 425053

Try this:

List<Predicate<String>> predicates = Arrays.asList(this::compute1, this::compute2, ...);

boolean anyTrue(String str) {
    return predicates.stream()
      .anyMatch(p -> p.test(str));
}

This returns true when the first predicate returns true.

Use the method as a filter predicate:

someStringStream.filter(this::anyTrue)...

Upvotes: 1

Related Questions