判断 java 8 Set null 和 非空 但是size()=0

在 Java 8 中,判断一个Set是否为null、是否为空集(size() == 0)但非null,核心就是分两步走:先判断是否为null,再判断是否为空。


一、常见写法

最常用:双重判空(安全写法)

java

Set<Long> set = getSet(); if (set == null) { System.out.println("Set 是 null(对象不存在)"); } else if (set.isEmpty()) { System.out.println("Set 非 null,但是空集(size = 0)"); } else { System.out.println("Set 非 null,且有元素,size = " + set.size()); }

一行式判空(适用于需要快速确认是否有数据)

java

if (set != null && !set.isEmpty()) { // 有数据 } else { // 无数据(可能是 null 也可能是 empty) }

二、nullvsempty行为对比

状态代码示例set == nullset.isEmpty()可安全调用
nullSet<Long> set = null;✅ true❌ 抛 NPE
空集Set<Long> set = new HashSet<>();❌ false✅ true
有元素Set<Long> set = new HashSet<>(Arrays.asList(1L, 2L));❌ false❌ false

三、实际应用场景

场景1:方法返回 Set,调用方安全使用

java

public void processIds(Set<Long> ids) { // 防御性编程:先判 null,再判空 if (ids == null || ids.isEmpty()) { System.out.println("没有数据需要处理"); return; } for (Long id : ids) { System.out.println("处理: " + id); } }

场景2:从数据库查询返回的 Set

java

Set<Long> orderIds = orderService.findOrderIdsByUser(userId); // 很多框架(如 Spring Data JPA、MyBatis)查询不到数据时返回空集合,而不是 null if (orderIds.isEmpty()) { System.out.println("该用户没有订单"); } else { System.out.println("共有 " + orderIds.size() + " 个订单"); }

场景3:结合你之前的 Feign 调用场景

java

Set<Long> organizationIds = organizationService.getOrgIds(); // 判断是否为空集 if (organizationIds != null && !organizationIds.isEmpty()) { // 传入 SQL 的 IN 子句 sql.append("AND organization_id IN (:organizationIds)"); query.setParameter("organizationIds", organizationIds); } else { // 不添加 IN 条件,避免生成 IN () 导致 SQL 错误 }

四、工具类封装(推荐)

如果项目中频繁判空,可以用 Hutool 或自定义工具类:

使用 Hutool(你项目已引入)

java

import cn.hutool.core.collection.CollUtil; if (CollUtil.isNotEmpty(organizationIds)) { // 非 null 且非空 }

自定义工具类

java

public class CollectionUtils { public static boolean isEmpty(Set<?> set) { return set == null || set.isEmpty(); } public static boolean isNotEmpty(Set<?> set) { return !isEmpty(set); } } // 使用 if (CollectionUtils.isNotEmpty(organizationIds)) { // 有数据 }

五、nullvsempty的最佳实践

原则说明
方法返回值优先返回空集合(如Collections.emptySet()),而不是null,减少调用方判空负担
方法入参如果业务不允许null,用@NotNull注解 + 提前校验,或在方法内判空
SQL 拼接传入IN子句前,务必检查!set.isEmpty(),避免生成IN ()导致语法错误
使用工具类统一用CollUtil.isNotEmpty(set)等工具方法,代码更简洁

六、总结

需要判断的场景推荐写法
需要区分 null 和 emptyif (set == null) { ... } else if (set.isEmpty()) { ... }
只关心是否有数据if (set != null && !set.isEmpty()) { ... }
使用 Hutoolif (CollUtil.isNotEmpty(set)) { ... }
SQL 传入 IN 前判断if (set != null && !set.isEmpty()) { sql.append("... IN (:ids)"); }

关键点nullempty是两种完全不同的状态:

  • null:对象不存在,调用任何方法都会抛 NPE

  • empty:对象存在,但无元素,isEmpty()返回true