美文网首页
判断字符串和List集合是否为空

判断字符串和List集合是否为空

作者: 久伴我还是酒伴我 | 来源:发表于2019-04-17 16:04 被阅读0次

    简介

    对于Java程序猿来说写后端代码,莫过于后端要做各种非空校验,经常写不等于Null且不等于空,集合要先判断不等于Null,长度还要大于0,感觉很Low,怎么改变这种Low的写法,咱们还是一个字:

    String字符串的为空判断

    \color{red}{比如}:if (null != val && !val.equalls(""))
    我们可以写成 if (StringUtils.isNotEmpty(val)) 这样的,但这样有一个问题,如果你的val值为“ ”,中间有一个空格,isNotEmpty 是判断不出来的,有可能判断出来的不准确,我们还可以使用 if (StringUtils.isNotBlank(val)) ,这样不仅对Null 和空字符串做了判断,还对空字符串中带有空格的做了判断。

    \color{red}{简单可以归纳为:}

    if ( StringUtils.isNotEmpty(str) ) 等价于 str != null && str.length > 0
    if ( StringUtils.isNotBlank(str) ) 等价于 str != null && str.length > 0 && str.trim().length > 0
    if ( StringUtils.isEmpty(str)  ) 等价于 str == null || str.length == 0
    if ( StringUtils.isBlank(str)  )  等价于 str == null || str.length == 0 || str.trim().length == 0
    

    List集合的为空判断

    \color{red}{比如}:if(null != list && list.size() >0) 可以写成 if (CollectionUtils.isNotEmpty(vas))

    \color{red}{简单可以归纳为:}

    if (CollectionUtils.isNotEmpty(vas)) 等价于 vas  != null && vas.size() >0
    if (CollectionUtils.isEmpty(vas)) 等价于 vas  == null || vas.size() ==0
    

    Map类型为空判断

    if ( MapUtils.isNotEmpty(map) ) 等价于 map != null && map.size() >0
    if ( MapUtils.isEmpty(id) ) 等价于 map == null && map.size() ==0
    

    引用包

    import org.apache.commons.collections.CollectionUtils;
    import org.apache.commons.lang.StringUtils;
    import org.apache.commons.collections.MapUtils;
    

    结束语

    就是把日常的总结记录下来,其实算不上指导性文章。

    相关文章

      网友评论

          本文标题:判断字符串和List集合是否为空

          本文链接:https://www.haomeiwen.com/subject/snenwqtx.html