I have a class with a collection of Seed
elements. One of the method's return type of Seed
is Optional<Pair<Boolean, String>>
.
I'm trying to loop over all seeds
, find if any boolean
value is true
and at the same time, create a set with all the String
values. For instance, my input is in the form Optional<Pair<Boolean, String>>
, the output should be Optional<Signal>
where Signal
is like:
class Signal {
public boolean exposure;
public Set<String> alarms;
// constructor and getters (can add anything to this class, it's just a bag)
}
This is what I currently have that works:
// Seed::hadExposure yields Optional<Pair<Boolean, String>> where Pair have key/value or left/right
public Optional<Signal> withExposure() {
if (seeds.stream().map(Seed::hadExposure).flatMap(Optional::stream).findAny().isEmpty()) {
return Optional.empty();
}
final var exposure = seeds.stream()
.map(Seed::hadExposure)
.flatMap(Optional::stream)
.anyMatch(Pair::getLeft);
final var alarms = seeds.stream()
.map(Seed::hadExposure)
.flatMap(Optional::stream)
.map(Pair::getRight)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
return Optional.of(new Signal(exposure, alarms));
}
Now I have time to make it better because Seed::hadExposure
could become and expensive call, so I was trying to see if I could make all of this with only one pass. I've tried (some suggestions from previous questions) with reduce
, using collectors (Collectors.collectingAndThen
, Collectors.partitioningBy
, etc.), but nothing so far.