Java Consumer accept()

🎓 Check Out My Top 25 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare

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.

My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare