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

Method References as Consumers

Using method references like System.out::println as Consumer implementations for cleaner code.

Method References as Consumers

What you'll learn: How to use method references like System.out::println as cleaner, more readable Consumer implementations.

The Core Idea

You've already seen that you can create Consumer instances using lambda expressions like s -> System.out.println(s). But when your lambda simply passes its parameter directly to a single method, Java offers a shortcut: method references. Instead of writing the lambda, you can reference the method directly using the :: operator.

This works because a Consumer accepts one argument and returns nothing—exactly what many void methods do. The method reference System.out::println is functionally identical to s -> System.out.println(s), but it's shorter and often clearer.

Common Method Reference Patterns as Consumers

When a method takes one parameter and returns void, it naturally fits the Consumer contract:

List<String> names = List.of("Alice", "Bob", "Charlie");

// Lambda version
names.forEach(name -> System.out.println(name));

// Method reference version - cleaner!
names.forEach(System.out::println);

This works with instance methods too:

List<String> items = new ArrayList<>();
items.add("apple");

// Lambda
names.forEach(item -> items.add(item));

// Method reference
names.forEach(items::add);

Why Use Method References?

Method references eliminate unnecessary lambda ceremony when you're just passing a parameter straight through. They make your intent clearer: "for each element, print it" reads naturally as forEach(System.out::println). Think of it as removing the middleman—you're directly connecting the Consumer to the action it should perform.

Key Takeaway: When your Consumer lambda simply passes its argument to a single method, replace it with a method reference using :: for cleaner, more readable code. System.out::println is the canonical example, but any void method with one parameter qualifies.