Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Java Collection Iteration Patterns: Iterator, Enhanced For, and Lambda Streams

Tech May 13 1

Iterator Fundamentals

java.util.Iterator<E> exposes three core operations:

  • boolean hasNext() – indicates whether another element is available.
  • E next() – returns the current element and advances the cursor; throws NoSuchElementException when exhausted.
  • void remove() – deletes the element most recently returned by next(); throws IllegalStateException if invoked without a preceding next() or after a prior remove().

Basic Traversal Example

import java.util.List;
import java.util.Iterator;

public class IteratorDemo {
    public static void main(String[] args) {
        List<String> basket = List.of("Apple", "Banana", "Cherry");
        Iterator<String> cursor = basket.iterator();

        while (cursor.hasNext()) {
            String item = cursor.next();
            if ("Banana".equals(item)) {
                cursor.remove();   // safe removal during iteration
            }
        }
        System.out.println(basket); // [Apple, Cherry]
    }
}

Enhanced For Loop

Introduced in Java 5, the enhanced for loop hides the iterator boilerplate behind syntactic sugar:

for (Type variable : iterable) {
    // body
}

Example:

List<String) tags = List.of("java", "python", "go");
for (String tag : tags) {
    System.out.println(tag.toUpperCase());
}

Limitations

  • Read-only access; structural modifications trigger ConcurrentModificationException.
  • No index or iterator reference available for removal or replacement.

Lambda Expressions & Streams

Java 8 introduced functional iteration via the Stream API:

List<Integer> numbers = List.of(3, 7, 1, 9, 4);

// print all
numbers.stream().forEach(n -> System.out.println(n));

// filter and print
numbers.stream()
       .filter(n -> n % 2 == 0)
       .forEach(System.out::println);

Stream Pipeline Components

Stage Purpose Example
Source Origin of data collection.stream()
Intermediate Transform/filter elements .filter(...), .map(...)
Terminal Produce result or side effect .forEach(...), .collect(...)

Complex Lambda Example

record Book(String title, int year) {}

List<Book> library = List.of(
    new Book("Effective Java", 2001),
    new Book("Clean Code", 2008),
    new Book("Java Concurrency", 2006)
);

library.stream()
       .filter(b -> b.year() >= 2005)
       .map(Book::title)
       .sorted()
       .forEach(System.out::println);

Choosing the Right Approach

Scenario Recommended Pattern
Simple read-only traversal Enhanced for loop
Need to remove elements Explicit Iterator with remove()
Complex filtering/transformation Stream + Lambda
Paralel processing parallelStream() with caution

Safe Removal Patterns

// Iterator removal
Iterator<String> it = list.iterator();
while (it.hasNext()) {
    if (it.next().startsWith("_")) {
        it.remove();
    }
}

// Stream-based removal (creates new list)
List<String> cleaned = list.stream()
                           .filter(s -> !s.startsWith("_"))
                           .collect(Collectors.toList());
Tags: Java

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.