Java Consumer accept()

In this guide, you will learn about the Consumer accept() method in Java programming and how to use it with an example.

1. Consumer accept() Method Overview

Definition:

The Consumer.accept() method is an abstract method from the Consumer functional interface. It defines an operation that accepts a single input argument and returns no result, essentially allowing side effects.

Syntax:

void accept(T t)

Parameters:

- t: The input argument.

Key Points:

- The Consumer interface is used primarily when you want to do something with an input and not return anything.

- It's often used with Java Streams, especially with the forEach() method.

- Since Consumer is a functional interface, it can be used in contexts expecting a lambda or method reference.

2. Consumer accept() Method Example

import java.util.function.Consumer;
import java.util.List;

public class ConsumerAcceptExample {
    public static void main(String[] args) {
        Consumer<String> printConsumer = s -> System.out.println("Name: " + s);

        List<String> names = List.of("John", "Jane", "Jack", "Jill");
        names.forEach(printConsumer::accept);
    }
}

Output:

Name: John
Name: Jane
Name: Jack
Name: Jill

Explanation:

In the given example, we define a Consumer named printConsumer which takes a string input (in this case, a name) and prints it. We then have a list of names which we process using the forEach() method. Within forEach(), we use a method reference to call the accept() method of our printConsumer. As a result, each name in the list is printed out.

Comments