OrElseGet chaining in Java8

5.3k Views Asked by At

I have a list in which 50 values are coming. Now I have 3 matching conditions, however matching conditions have some order. Like for P1 condition I have to match first, if it does not matches in any element then second condition should be evaluated for logic and so on. How to do this using Java 8 and orElseGet chaining.

I was considering to use orElseGet, but it requires a supplier.

Please let me know how to do it.

1

There are 1 best solutions below

0
On BEST ANSWER

The simplest way would be to iterate over the conditions first:

Stream.<Predicate<String>>of("AB"::equals, "DC"::equals,"XY"::equals)
        .flatMap(condition -> test.stream().filter(condition).limit(1))
        .findFirst()
        .orElse(test.get(0));

Of course, since in your sample case all conditions are matches to strings, you could do this simpler, but I assume you mean to ask about a general case.

You can also do it with orElseGet:

test.stream().filter("AB"::equals).findFirst()
        .map(Optional::of).orElseGet(() -> test.stream().filter("DC"::equals).findFirst())
        .map(Optional::of).orElseGet(() -> test.stream().filter("XY"::equals).findFirst())
        .orElse(test.get(0));