OrElseGet chaining in Java8
I have a list that comes with 50 values. Now I have 3 matching conditions, however the matching conditions are in some order. As with condition P1, I have to match first, if it doesn't match any item, then the second condition has to be evaluated for logic and so on. How to do it using Java 8 chaining and orElseGet
.
I was considering using it orElseGet
, but it requires a vendor.
Please let me know how to do this.
source to share
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 example example all the conditions match strings, you can make it easier, but I assume you want to ask about the 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));
source to share