I need to do a series of null checks ( nested null-checks ) to get an array of strings like below
String[] test;
if(CollectionUtils.isNotEmpty(checkList)){
if(MapUtils.isNotEmpty(checkList.get(0))){
if(StringUtils.isNotBlank(checkList.get(0).get("filename"))){
test = checkList.get(0).get("filename").split("_");
}
}
}
Is there a better way, maybe using Java8 Optional, to perform these kind of nested checks? I unsuccessfully tried to use Optional with flatmap / map.
!checkList.isEmpty()will return an NPE. I thought I would have to docheckList!= null && !checkList.isEmpty(), so I used the other library. So for this checking, must I have the nestedif()statements?return Optional.ofNullable(checkList) .filter(l -> !l.isEmpty()) .map(l -> l.get(0)) .filter(m -> !m.isEmpty()) .map(e -> e.getOrDefault("filename", "").split("_")) .orElse(new String[10]);which is not good unless you know, why those hardcoded values are floating in.nullin the first place. Then, you don’t need 3rd party methods performingnullchecks.