如何判断List 集合和Map 集合是否为空

导读:本篇文章讲解 如何判断List 集合和Map 集合是否为空,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

1:废话少说,直接上代码

  	    //使用CollectionUtils Spring 包下的工具类
		List<Object> list = new ArrayList<>();

		if (list.isEmpty()) {
			log.info("当前的CollectionUtils-->{}",list.isEmpty());
		}

		if (CollectionUtils.isEmpty(list)){
			log.info("当前的CollectionUtils-->{}",CollectionUtils.isEmpty(list));
		}

		//ObjectUtils  Spring 包下的工具类
		if (ObjectUtils.isEmpty(list)) {
			log.info("当前的ObjectUtils-->:{}",ObjectUtils.isEmpty(list));
		}

执行结果如下:

如何判断List 集合和Map 集合是否为空

 1.1:特殊情况

        ArrayList<Object> list1 = new ArrayList<>();
		list1 = null;
		try{
			//如果将list1 置为 null  进行判断非空的情况下 可以使用Objects.isNull()  方法
			if (Objects.isNull(list1)){
				log.info("Objects.isNull-->{}",Objects.isNull(list1));
			}
			//如果调用  isEmpty() 方法进行判断非空的情况下 就会报空指针异常, 报错异常原因如下
			if (list1.isEmpty()) {
				log.info("list1.isEmpty()-->,{}",list1.isEmpty());
			}
		}catch (Exception e) {
			log.info("Exception-->",e);
		}

     

打印结果如下:

如何判断List 集合和Map 集合是否为空

 调用isEmpty 方法报错原因如下:

此时使用isEmpty()是出现了空指针异常NullpointException;原来isEmpty()用来判断一个变量是否已经初始化了,因为 “” 和new 的时候系统都会为其分配内存, 不管是否有值,当为null的时候,系统的不会为其分配内存,这是它是不存在的,如果调用isEmpty()方法时JDK根本不知道这是什么所以会报空指针异常;所以使用该方法判断之前应先判断是否为null

2:Map 集合

	   Map<String,String> map = new HashMap();
//		map.put("1","xia");

		if (map.isEmpty()){
			log.info("map.isEmpty-->{}", map.isEmpty());   //为真打印True
		}else {
			log.info("map.isEmpty-->{}", map.isEmpty());   //为假打印FALSE
		}

		//判断map 集合中是否 存在 键值为: 1  的数据
		if (map.containsKey("1")) {
			log.info("map.containsKey-->{}", map.get(1));
		}

		//  使用ObjectUtils 来判断map 集合是否为空
 		if (ObjectUtils.isEmpty(map)) {
			log.info("当前的ObjectUtils集合为空:{}",map.isEmpty());
		}

		//判断map 集合中的value 值是否为空
		map.put("2","");
		if ("".equals(map.get("2"))) {
			log.info("当前的value值为:{}", map.get(2));
		}

打印结果如下:

如何判断List 集合和Map 集合是否为空

 2.1:特殊情况

	    HashMap<Object, Object> map1 = new HashMap<>();
		map1 = null;
		try {

			if (Objects.isNull(map1)) {
				log.info("Objects.isNull-->{}",Objects.isNull(map1));
			}

			if (ObjectUtils.isEmpty(map1)) {
				log.info("ObjectUtils.isEmpty-->{}",ObjectUtils.isEmpty(map1));
			}

			if (map1.isEmpty()) {
				log.info("当前的map集合为空:{}",map1.isEmpty());
			}

		}catch (Exception e) {
			// 此时使用isEmpty()是出现了空指针异常NullpointException;
			// 原来isEmpty()用来判断一个变量是否已经初始化了,
               因为 “” 和new 的时候系统都会为其分配内存,
			// 不管是否有值,当为null的时候,系统的不会为其分配内存,这是它是不存在的,
			// 如果调用isEmpty()方法时JDK根本不知道这是什么所以会报空指针异常;
			// 所以使用该方法判断之前应先判断是否为null
		    log.error("报错了,{}",e);
		}

打印结果如下:(当map = null  ,调用isEmpty 报错)

如何判断List 集合和Map 集合是否为空

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由半码博客整理,本文链接:https://www.bmabk.com/index.php/post/121383.html

(0)

相关推荐

发表回复

登录后才能评论
半码博客——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!