Java 8 nested null check for a string in a map in a list

adbdkb :

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.

John Kugelman :

You could use a long chain of Optional and Stream operations to transform the input step by step into the output. Something like this (untested):

String[] test = Optional.ofNullable(checkList)
    .map(Collection::stream)
    .orElseGet(Stream::empty)
    .findFirst()
    .map(m -> m.get("filename"))
    .filter(f -> !f.trim().isEmpty())
    .map(f -> f.split("_"))
    .orElse(null);

I'd strongly encourage you to stop using null lists and maps. It's a lot better to use empty collections rather than null collections, that way you don't have to have null checks all over the place. Furthermore, don't allow empty or blank strings into your collections; filter them out or replace them with null early, as soon as you're converting user input into in-memory objects. You don't want to have to insert calls to trim() and isBlank() and the like all over the place.

If you did that you could simplify to:

String[] test = checkList.stream()
    .findFirst()
    .map(m -> m.get("filename"))
    .map(f -> f.split("_"))
    .orElse(null);

Much nicer, no?

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=93137&siteId=1