Various ways to iterate over Collections in Java ✅
Basic Loops👉
Traditional indexed for loops work for indexed collections like List and arrays by using size() or length and get(index). While loops pair with iterators via hasNext() and next(). These approaches allow index access or safe removal during iteration.
Enhanced For-Each👉
The enhanced for loop (for-each), introduced in Java 5, simplifies iteration over any Iterable or array without explicit indexing: for (Type item : collection) { ... }. It suits read-only traversal of List, Set, or arrays cleanly.
Iterator and forEach👉
Explicit Iterator from iterator() enables fail-fast iteration and removal: while (it.hasNext()) { it. next(); }. Java 8's forEach(Consumer) method processes each element concisely, like list.forEach(System.out::println);, on List, Set, or Map views.
Streams API👉
Java 8 Streams provide functional iteration: collection. stream().forEach(...) or with operations like filter/map: stream().filter(...).forEach(...). Use parallelStream() for concurrency on large collections.
Map Iteration 👉
For Maps, iterate entries via entrySet(): for (Map.Entry<K,V> e : map.entrySet()) { ... }, keys with keySet(), or values with values(). Streams work similarly: map.entrySet().stream().forEach(...)