Java.Collections.What are the ways to iterate over list elements?

✅ 1. Enhanced for loop (for-each loop)

List<String> list = List.of("apple", "banana", "cherry");

for (String item : list) {
    System.out.println(item);
}

Clean and readable

Can’t modify the list (no remove() here)

✅ 2. Classic for loop (index-based)

for (int i = 0; i < list.size(); i++) {
    System.out.println(list.get(i));
}

Good when you need the index

Allows read and write access (list.set(i, newValue))

✅ 3. Iterator

Iterator<String> it = list.iterator();
while (it.hasNext()) {
    String item = it.next();
    System.out.println(item);
}

Use it.remove() to safely remove items during iteration

✅ 4. ListIterator (bi-directional iterator)

ListIterator<String> it = list.listIterator();
while (it.hasNext()) {
    System.out.println(it.next());
}
while (it.hasPrevious()) {
    System.out.println(it.previous());
}

Can go forward and backward

Can modify the list (add(), set(), remove())

✅ 5. Java 8+ forEach() with lambda

list.forEach(item -> System.out.println(item));

Clean, functional

Read-only (can’t modify structure during iteration)

✅ 6. Stream API

list.stream()
    .filter(item -> item.startsWith("a"))
    .forEach(System.out::println);

✅ 7. Using a forEachRemaining() from Iterator (Java 8+)

Iterator<String> it = list.iterator();
it.forEachRemaining(item -> System.out.println(item));

Less common, but neat for one-liners with iterators

🧠 TL;DR

MethodUse case
Enhanced for loopSimple read-only iteration
Classic for loopWhen you need indexes
IteratorWhen you may remove items while iterating
ListIteratorBi-directional or advanced list edits
forEach()Clean, lambda-based read access
Stream APIFiltering, transforming, chaining
This entry was posted in Без рубрики. Bookmark the permalink.