Course contentsShow
← Java
Lesson 1660 of 2,87035. Functional InterfacesFree lesson

Consumer in forEach: Iterating Collections

How Consumer enables the forEach method on collections and streams for element processing.

Consumer in forEach: Iterating Collections

You'll learn how the Consumer functional interface powers the forEach method to process every element in a collection.

The Connection Between Consumer and forEach

The forEach method you've been using on collections and streams actually takes a Consumer<T> as its parameter. When you call forEach, you're passing a Consumer that defines what action to perform on each element. This is why lambdas and method references work so naturally with forEach — they're creating Consumer implementations behind the scenes.

How It Works

Every time forEach visits an element, it calls the Consumer's accept method with that element. The signature looks like this:

void forEach(Consumer<? super T> action)

The forEach method iterates through the collection, passing each element to your Consumer.

Practical Examples

Using a lambda as a Consumer:

List<String> names = List.of("Alice", "Bob", "Carol");
names.forEach(name -> System.out.println(name));

Using a method reference:

names.forEach(System.out::println);

Storing a Consumer explicitly:

Consumer<String> printer = name -> System.out.println("Hello, " + name);
names.forEach(printer);

Chaining operations with andThen:

Consumer<String> logger = name -> System.out.println("Processing: " + name);
Consumer<String> counter = name -> System.out.println("Length: " + name.length());

names.forEach(logger.andThen(counter));

This demonstrates that forEach isn't magic — it's simply applying a Consumer to each element in sequence.

Key Takeaway: The forEach method works by accepting a Consumer<T> parameter and calling its accept method on each element, making iteration declarative and functional rather than imperative.