Basically,I need to get a size of optional list in an optional object. Something like:
private int getCount(@NonNull Optional<myObject> aaa) {
if(aaa.isPresent() && aaa.get().getMyList().isPresent()) {
return aaa.get().getMyList().get().size();
}
return 0;
}
The code doesn't look nice. What's the elegant way to get it? With ifPresent().orElse()? Thanks in advance!
CodePudding user response:
Consecutive map
operations, and a final orElse
:
private int getCount(@NonNull Optional<myObject> cvm) {
return cvm
.map(x -> x.getMyList())
.map(list -> list.size()) // or List::size
.orElse(0);
}