简体   繁体   English

Java 8嵌套null检查列表中映射中的字符串

[英]Java 8 nested null check for a string in a map in a list

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? 有没有更好的方法(也许使用Java8 Optional)来执行此类嵌套检查? I unsuccessfully tried to use Optional with flatmap / map. 我尝试将Optional与flatmap / map结合使用失败。

You could use a long chain of Optional and Stream operations to transform the input step by step into the output. 您可以使用一长串的OptionalStream操作将输入逐步转换为输出。 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. 我强烈建议您停止使用null列表和地图。 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. 这是一个很大更好地使用的集合,而不是的集合,这样你就不必有null检查所有的地方。 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. 将用户输入转换为内存中对象后,立即将其过滤掉或将其替换为null You don't want to have to insert calls to trim() and isBlank() and the like all over the place. 您不需要isBlank()都插入对trim()isBlank()等的调用。

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? 好多了,不是吗?

Don't nest the if s, but just unwrap and invert them: 不要嵌套if ,而是将它们解开并反转:

String[] defaultValue = // let this be what ever you want

if(checkList == null || checkList.isEmpty()) {
    return defaultValue;
}

Map<String, String> map = checkList.get(0);
if(map == null || map.isEmpty()) {
    return defaultValue;
}

String string = map.get("filename");
if(string == null || string.trim().isEmpty()) {
    return defaultValue;
}

return string.split("_");

Though this only works when you wrap this extraction logic in a method: 虽然这仅在将提取逻辑包装在方法中时才有效:

public static String[] unwrap(List<Map<String, String>> checkList) {
    ...
}

If checkList is null, it will throw null pointer exception on CollectionUtils.isNotEmpty(checkList). 如果checkList为null,它将在CollectionUtils.isNotEmpty(checkList)上引发空指针异常。 Also use in-built empty checker. 还要使用内置的空检查器。 Better you should code 更好的是你应该编码

        if (null != checkList && !checkList.isEmpty() 
                && null != checkList.get(0) && !checkList.get(0).isEmpty()
                && StringUtils.isNotBlank(checkList.get(0).get("filename"))) {

            test = checkList.get(0).get("filename").split("_");

        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM