Igor Igor - 4 years ago 126
Java Question

Java Stream: how to pass Set to Stream.of() and call method on each elemnt?

i have such old-style code:

if (setContainer.getSet() == null) {
return null;
}
for (SetElement setElement : setContainer.getSet()){
if ("SomeString".equals(SetElement.getCode())) {
return setElement.getValue();
}
}
return null;


i've tried this but it doesnt check if Set is null:

setContainer.getSet()
.stream()
.filter(setValue -> "SomeValue".equals(setElement.getCode()))
.map(SetElement::getValue)
.findAny()
.orElse(null) ;


as i understand, i should use
Stream.of()

but i dont understand how to perform code as above, because it always returns
Optional<Set<SetElement>>

Answer Source

You can use Optional.ofNullable to achieve this:

return Optional.ofNullable(setContainer.getSet())
    .flatMap(set -> set.stream()
        .filter(e ->  "SomeValue".equals(e.getCode()))
        .map(SetElement::getValue)
        .findAny())
    .orElse(null);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download