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及以上)
相关推荐
派大鑫wink15 小时前
【JAVA学习日志】SpringBoot 参数配置:从基础到实战,解锁灵活配置新姿势
java·spring boot·后端
程序员爱钓鱼16 小时前
Node.js 编程实战:文件读写操作
前端·后端·node.js
xUxIAOrUIII16 小时前
【Spring Boot】控制器Controller方法
java·spring boot·后端
PineappleCoder16 小时前
工程化必备!SVG 雪碧图的最佳实践:ID 引用 + 缓存友好,无需手动算坐标
前端·性能优化
Dolphin_Home16 小时前
从理论到实战:图结构在仓库关联业务中的落地(小白→中级,附完整代码)
java·spring boot·后端·spring cloud·database·广度优先·图搜索算法
zfj32116 小时前
go为什么设计成源码依赖,而不是二进制依赖
开发语言·后端·golang
weixin_4624462316 小时前
使用 Go 实现 SSE 流式推送 + 打字机效果(模拟 Coze Chat)
开发语言·后端·golang
JIngJaneIL16 小时前
基于springboot + vue古城景区管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot·后端
敲敲了个代码17 小时前
隐式类型转换:哈基米 == 猫 ? true :false
开发语言·前端·javascript·学习·面试·web
澄江静如练_17 小时前
列表渲染(v-for)
前端·javascript·vue.js