Menu

Java Iterating Collections: for-each, Iterator, forEach

The ways to loop over Java collections - the for-each loop, the Iterator, index loops, and the forEach method - and how to remove elements safely while iterating.

This page includes runnable editors - edit, run, and see output instantly.

One Job, Several Tools

You have collected some data - in an ArrayList, a HashSet, a HashMap - and now you want to visit every element. Java gives you a few ways to do that, and which one you pick depends on whether you need the index, whether you need to remove items mid-loop, and whether you prefer a method-style or loop-style syntax.

The good news: every Collection (list, set, queue) supports the same enhanced for loop, so once you learn it you can iterate them all the same way.

Read the colon as "in": "for each lang in langs". You never touch an index, so there is nothing to get wrong.

The for-each Loop

The enhanced for is the default choice for plain "do something with each element". It reads cleanly and works identically across collection types - here a HashSet, which has no indices at all:

One thing to remember about a HashSet: it has no defined order, so the elements may print in any sequence. The for-each visits them all exactly once regardless.

When You Need the Index

The for-each gives you the element but not its position. If you genuinely need the index - to number lines, or to look at neighbouring elements - use a counted loop with size() and get(i). This works on a List, which is positional; sets and maps have no index, so this style does not apply to them.

Do not reach for this just out of habit. If you are not using i for anything beyond get(i), the for-each version is shorter and harder to get wrong.

Iterating a Map

A Map is not a Collection, so you cannot for-each over it directly. Instead you loop over one of its three views. The most common is entrySet(), which hands you each key-value pair together:

If you only need the keys, loop ages.keySet(); if you only need the values, loop ages.values(). Prefer entrySet() when you need both - looping the keys and then calling ages.get(key) inside does a second lookup on every iteration for no reason.

The Iterator

The for-each is actually syntactic sugar over an Iterator - an object that walks a collection one element at a time via hasNext() and next(). You rarely write this loop by hand, with one important exception: it is the safe way to remove elements while iterating.

it.remove() deletes the element that next() last returned, and the iterator stays valid. This is the only sanctioned way to mutate a collection during a manual loop.

The Trap: ConcurrentModificationException

If you call add or remove on the collection itself inside a for-each loop, you get a ConcurrentModificationException - the iterator notices the collection changed underneath it and refuses to continue. This is one of the most common beginner errors, and like any runtime exception it aborts the method unless you avoid triggering it.

List<Integer> nums = new ArrayList<>(List.of(1, 2, 3, 4));
for (int n : nums) {
    if (n % 2 == 0) {
        nums.remove(Integer.valueOf(n));   // throws ConcurrentModificationException
    }
}

The fix is almost always removeIf, which expresses the intent in one line and handles the iteration for you:

removeIf works on any Collection, so the same call cleans up a HashSet too.

The forEach Method

Every collection also has a forEach method that takes a lambda and runs it on each element. It is a more functional, expression-style alternative to the loop - handy for short one-liners:

Note that Map.forEach takes a two-argument lambda (key, value) directly - no entrySet() needed. Use forEach for quick side effects; reach back for the regular for loop when the body grows or you need to break out early, which a lambda cannot do.

Next: Methods

You have now packaged data into collections and walked over it every way Java offers. The next step is packaging behaviour: writing your own methods so you can name a block of logic, hand it inputs, and reuse it - which is the next page.

Frequently Asked Questions

How do you loop over a list in Java?

The cleanest way is the enhanced for loop (for-each): for (String s : list) { ... }. It works on any Collection - ArrayList, HashSet, and so on. Use an index loop with get(i) only when you actually need the position, and an Iterator when you need to remove elements during the loop.

How do you iterate over a HashMap in Java?

A Map is not a Collection, so loop over one of its views. The usual choice is for (Map.Entry<K, V> e : map.entrySet()), which gives you both the key (e.getKey()) and value (e.getValue()) in one pass. You can also loop map.keySet() for keys or map.values() for values.

Why do I get a ConcurrentModificationException when looping?

You called add or remove on the collection while a for-each loop was iterating it. The for-each loop uses an Iterator under the hood and it detects that the collection changed structurally. Fix it by removing through the Iterator's own remove() method, or by calling removeIf(...) instead of looping.

Coddy programming languages illustration

Learn to code with Coddy

GET STARTED