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:

.filter(setValue -> "SomeValue".equals(setElement.getCode()))
.orElse(null) ;

as i understand, i should use

but i dont understand how to perform code as above, because it always returns

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()))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download