Java 8嵌套null检查列表中映射中的字符串 [英] Java 8 nested null check for a string in a map in a list

查看:76
本文介绍了Java 8嵌套null检查列表中映射中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要进行一系列的空检查(嵌套的空检查)以获取如下所示的字符串数组

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("_");
        }
    }
}

是否存在更好的方法(也许使用Java8 Optional)来执行此类嵌套检查?我尝试将Optional与flatmap/map结合使用失败.

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.

推荐答案

您可以使用长链的OptionalStream操作将输入逐步转换为输出.像这样(未经测试):

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);

我强烈建议您停止使用null列表和地图.与 null 集合相比,使用 empty 集合要好得多,这样一来,您不必到处都进行null检查.此外,请勿在您的集合中使用空字符串或空白字符串.将用户输入转换为内存对象后,请尽早将其过滤掉或用null替换.您不需要到处都插入对trim()isBlank()之类的调用.

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);

好多了,不是吗?

这篇关于Java 8嵌套null检查列表中映射中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆