判空方法分享

新年 Java经验 发布时间:2024-02-09 23:37:02 阅读数:9632 1
下文笔者讲述java中对字符串,list, Map是否为空的判断方法分享,如下所示
1.引入commons-lang3,jar包
2.使用其中的方法,即可对这些对象进行非空判断
例:
一、字符串pank

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version> <!-- 替换为最新版本号 -->
</dependency>

import org.apache.commons.lang3.StringUtils;

public class Main {
    public static void main(String[] args) {
        String myString = "Hello, World!";

        // 判断字符串是否为空
        if (StringUtils.isEmpty(myString)) {
            System.out.println("字符串为空");
        } else {
            System.out.println("字符串不为空");
        }

        // 判断字符串是否为空或只包含空格
        if (StringUtils.isBlank(myString)) {
            System.out.println("字符串为空或只包含空格");
        } else {
            System.out.println("字符串不为空且不只包含空格");
        }
    }
}

二、List判空
import org.apache.commons.collections

// List判空
List<String> myList = new ArrayList<>();
if (CollectionUtils.isEmpty(myList)) {
    System.out.println("List为空");
} else {
    System.out.println("List不为空");
}

三、Map
import org.apache.commons.collections.MapUtils

// Map判空
Map<String, Integer> myMap = new HashMap<>();
if (MapUtils.isEmpty(myMap)) {
    System.out.println("Map为空");
} else {
    System.out.println("Map不为空");
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202402/17074930877950.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者