233. Java 集合 - 遍历 Collection 中的元素

233. Java 集合 - 遍历 Collection 中的元素

在 Java 中,遍历集合(Collection)的方法有几种。不同方式适用于不同场景,比如只读遍历带元素删除的遍历等。


🚶 使用 for-each 遍历集合(最简单)

如果你只需要读取元素 ,使用for-each语法是最简单、最推荐的:

java 复制代码
Collection<String> strings = List.of("one", "two", "three");

for (String element : strings) {
    System.out.println(element);
}

🖨️ 输出

java 复制代码
one
two
three

优点

  • 简洁清晰
  • 没有索引管理的麻烦
  • 不容易出错

⚠️ 注意for-each 只适合读取元素 ,不能在遍历过程中修改集合(比如删除元素)。


🧹 使用 Iterator 遍历集合(可修改元素)

如果你需要在遍历时安全地删除元素 ,那么需要使用 Iterator

Iterator 遍历模式

java 复制代码
Collection<String> strings = List.of("one", "two", "three", "four");

for (Iterator<String> iterator = strings.iterator(); iterator.hasNext(); ) {
    String element = iterator.next();
    if (element.length() == 3) {
        System.out.println(element);
    }
}

🖨️ 输出

java 复制代码
one
two

🛠️ Iterator 的三个重要方法

方法 作用
hasNext() 判断是否还有下一个元素
next() 取出下一个元素(并移动光标)
remove() 删除当前元素(可选操作,并非所有集合都支持)

⚡ remove() 方法的使用

可变集合 (如 ArrayListLinkedListHashSet)中,可以通过 iterator.remove() 删除当前元素。

正确示例

java 复制代码
Collection<String> strings = new ArrayList<>(List.of("one", "two", "three", "four"));

Iterator<String> iterator = strings.iterator();
while (iterator.hasNext()) {
    String element = iterator.next();
    if (element.length() == 3) {
        iterator.remove(); // 删除长度为3的元素
    }
}

System.out.println(strings);

🖨️ 输出

java 复制代码
[three, four]

🚨 注意事项

  • 必须先调用 next() 再调用 remove()
  • 直接在集合上调用 remove()(而不是通过 iterator)将引发问题。

❗ 集合修改异常:ConcurrentModificationException

如果你在遍历过程中直接修改集合内容 (比如用 collection.remove() 而不是 iterator.remove()),就可能抛出 ConcurrentModificationException

来看一个错误示例:

java 复制代码
Collection<String> strings = new ArrayList<>();
strings.add("one");
strings.add("two");
strings.add("three");

Iterator<String> iterator = strings.iterator();
while (iterator.hasNext()) {
    String element = iterator.next();
    strings.remove(element); // ❌ 错误:直接修改集合
}

运行时抛出异常:

java 复制代码
Exception in thread "main" java.util.ConcurrentModificationException

🎯 正确的删除姿势

如果需要根据某个条件批量删除元素,推荐使用 removeIf() 方法(从 Java 8 开始提供):

java 复制代码
Collection<String> strings = new ArrayList<>(List.of("one", "two", "three", "four"));

strings.removeIf(s -> s.length() == 3);

System.out.println(strings);

🖨️ 输出

java 复制代码
[three, four]

这种写法更加现代、简洁、避免了繁琐的迭代器操作!


📌 小结

技术 适用场景 特点
for-each 循环 只读取元素 简洁高效,不能修改集合
Iterator 迭代器 需要在遍历时删除元素 支持安全删除,需注意正确调用顺序
removeIf(Predicate) 批量删除符合条件的元素 简洁优雅,推荐使用(Java 8及以上)
相关推荐
逝水无殇9 分钟前
C# 运算符重载详解
开发语言·后端·c#
苏三说技术29 分钟前
2026编程圈很火的10个Skills
后端
前端H31 分钟前
微前端 v3 架构升级:从加载隔离到状态协同
前端·架构·状态模式
用户83562907805136 分钟前
使用 Python 自动化 Excel 公式和函数:完整指南
后端·python
编程(变成)小辣鸡1 小时前
Spring事务失效场景
java·后端·spring
PinkSun1 小时前
MySQL 建表报 1030,能查不能建,排查 1 小时发现是我自己改了一行权限
后端
陆枫Larry2 小时前
小程序包体积优化:用 SVG 图片替换 iconfont,并保留 CSS 控色能力
前端
无相求码2 小时前
为什么 printf 可以接受任意数量参数?变长参数的底层真相
后端
郡杰2 小时前
Boot:MP|测验|结果封装|异常处理|前后联调|拦截器
后端
团团崽_七分甜2 小时前
后端基础概念 - 前端开发者指南(进程、线程、事务)
后端