Course contentsShow
← Java
Lesson 1491 of 2,87033. Streams API: Terminal OperationsFree lesson

forEach with Method References

Simplify forEach calls using method references like System.out::println for cleaner, more readable code.

forEach with Method References

What you'll learn: How to write cleaner, more concise forEach code by using method references instead of lambda expressions.


When you use forEach with a lambda expression like element -> System.out.println(element), you're essentially passing each stream element to a single method. Java provides a shorthand for this common pattern: method references.

From Lambda to Method Reference

Consider this standard forEach with a lambda:

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

Since the lambda simply takes name and passes it directly to println, you can replace it with a method reference:

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

The :: operator creates a reference to the println method. Java automatically passes each stream element to it.

Think of It Like a Pointer

Imagine you're directing traffic: instead of telling each car "you, turn left" individually, you just point at the left-turn sign. Method references work the same way—you're pointing to an existing method rather than writing out the instruction each time.

When to Use Method References

Method references work perfectly when your lambda:

  • Takes one parameter
  • Immediately passes it to a single method
  • Doesn't modify the parameter first

They make your code more readable by removing the "plumbing" (name ->) and showing just the action (System.out::println).

Key Takeaway: Method references like System.out::println replace simple lambda expressions in forEach, making terminal operations cleaner and eliminating boilerplate parameter declarations.