🎓 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:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment