After long time on Java 7 I am finally converting to Java 8. I am wondering though whats the best construct in this case: lets go directly to example:
class Bar {
private Foo foo;
// getters, setters
}
class Foo {
private String value1;
private String value2;
private String value3;
private String value4;
// getters, setters
}
What is the best option(al) for checking whether foo is not null and has at least one value filled?
1.
Optional<Foo> foo = Optional.ofNullable(bar.getFoo());
if(foo.map(Foo::getValue1).isPresent()
||foo.map(Foo::getValue2).isPresent()
||foo.map(Foo::getValue3).isPresent()
||foo.map(Foo::getValue4).isPresent()){
}
2.
Optional<Foo> foo = Optional.ofNullable(bar.getFoo());
if(foo.filter(foo->foo.getValue1()!=null
||foo.getValue2()!=null
||foo.getValue3()!=null
||foo.getValue4()!=null).isPresent()){
}
- or just use old good nullchecks
Foo foo1=bar.getFoo();
if(foo1!=null&&(foo.getValue1()!=null
||foo.getValue2()!=null
||foo.getValue3()!=null
||foo.getValue4()!=null)){
}
Thank you.