HashSet本身不提供过滤功能,需在添加前校验或用Stream/迭代器筛选有效元素;推荐添加时检查null、空字符串等无效状态,或用filter+collect生成新集合,避免ConcurrentModificationException。

HashSet 本身不提供过滤功能,它只是一个无序、不允许重复的集合容器。要“过滤掉为空或无效的元素”,实际是在添加前做判断,或在已有集合上筛选出有效元素并生成新集合。
添加时提前校验(推荐)
在把元素加入 HashSet 前,先判断是否为 null、空字符串、空集合、或自定义的“无效”状态(如对象字段全为空)。这样从源头避免无效数据进入。
- 对 String:检查
str != null && !str.trim().isEmpty() - 对集合/数组:检查
coll != null && !coll.isEmpty() - 对自定义对象:可重写一个
isValid()方法,比如要求 name 非空且 id > 0 - 示例:
Set<string> set = new HashSet(); String s = " "; if (s != null && !s.trim().isEmpty()) { set.add(s.trim()); }</string>
从已有 HashSet 中筛选有效元素
如果 HashSet 已含无效元素(如 null 或空串),可用 Stream API 创建新集合,保留符合条件的元素。
- Java 8+ 推荐写法:
Set<string> filtered = originalSet.stream() .filter(s -> s != null && !s.trim().isEmpty()) .collect(Collectors.toCollection(HashSet::new));</string> - 注意:不能在遍历原集合时直接调用
remove(),否则会抛ConcurrentModificationException - 若需就地清理(不创建新集合),可用迭代器安全删除:
Iterator<string> it = set.iterator(); while (it.hasNext()) { String s = it.next(); if (s == null || s.trim().isEmpty()) { it.remove(); // 安全删除 } }</string>
使用工具类或封装通用逻辑
若多处需要类似过滤,可封装成静态方法,提高复用性和可读性。
- 例如:
public static <t> Set<t> filterNonNull(Set<t> source, Predicate<t> isValid) { return source.stream().filter(isValid).collect(Collectors.toCollection(HashSet::new)); } // 使用 Set<string> clean = filterNonNull(set, s -> s != null && !s.trim().isEmpty());</string></t></t></t></t> - 也可结合 Apache Commons Lang 的
StringUtils.isNotBlank()简化字符串判断
特别注意 null 元素的处理
HashSet 允许存一个 null,但多数业务场景中它被视为无效。务必明确需求:
- 若业务逻辑允许 null,过滤条件中就不该排除它
- 若不允许,所有涉及该集合的判空、toString、equals 操作都可能 NPE,建议统一在入口拦截
- IDEA 或 Sonar 等工具可配置检查,提醒潜在 null 风险
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











