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

201 阅读2分钟

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

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


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

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

Collection<String> strings = List.of("one", "two", "three");

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

🖨️ 输出

one
two
three

优点

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

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


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

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

Iterator 遍历模式

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);
    }
}

🖨️ 输出

one
two

🛠️ Iterator 的三个重要方法

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

⚡ remove() 方法的使用

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

正确示例

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);

🖨️ 输出

[three, four]

🚨 注意事项

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

❗ 集合修改异常:ConcurrentModificationException

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

来看一个错误示例:

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); // ❌ 错误:直接修改集合
}

运行时抛出异常:

Exception in thread "main" java.util.ConcurrentModificationException

🎯 正确的删除姿势

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

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

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

System.out.println(strings);

🖨️ 输出

[three, four]

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


📌 小结

技术适用场景特点
for-each 循环只读取元素简洁高效,不能修改集合
Iterator 迭代器需要在遍历时删除元素支持安全删除,需注意正确调用顺序
removeIf(Predicate)批量删除符合条件的元素简洁优雅,推荐使用(Java 8及以上)