Issue
I have a class with a collection of Seed
elements. One of the method's return type of Seed
is Optional<Pair<Boolean, Boolean>>
.
I'm trying to loop over all seeds
, keeping the return type (Optional<Pair<Boolean, Boolean>>
), but I would like to be able to say if there was at least true
value (in any of the Pair
s) and override the result with it. Basically, if the collection is (skipping the Optional
wrapper to make things simpler): [Pair<false, false>
, Pair<false, true>
, Pair<false, false>
] I would like to return and Optional
of Pair<false, true>
because the second element had true
. In the end, I'm interested if there was a true
value and that's about it.
public Optional<Pair<Boolean, Boolean>> hadAnyExposure() {
return seeds.stream()
.map(Seed::hadExposure)
...
}
I was playing with reduce
but couldn't come up with anything useful.
My question is related with Java streams directly. I can easily do this with a
for
loop, but I aimed initially for streams.
Solution
Your thoughts on reduce
look like the right way to go, using ||
to reduce both sides of each Pair
together. (Not exactly sure what your Optional
semantics are, so going to filter out empty ones here and that might get what you want, but you may need to adjust):
Optional<Pair<Boolean, Boolean>> result = seeds.stream().map(Seed::hadExposure)
.filter(Optional::isPresent)
.map(Optional::get)
.reduce((a, b) -> new Pair<>(a.first || b.first, a.second || b.second));
Answered By - Joe
Answer Checked By - Cary Denson (JavaFixing Admin)