Consumers and Suppliers
Consumer and Supplier Interfaces in Java
Welcome to the lesson on "Consumers and Suppliers". As we continue to explore functional interfaces in Java, this lesson will introduce you to two key interfaces: Consumer and Supplier. Building on the foundational concepts you've learned so far, we'll dive into how these interfaces can be utilized effectively to make your code more modular and readable.
What You'll Learn
By the end of this lesson, you will feel comfortable using Consumer and Supplier interfaces to create more functional and modular code.
- Using the
Consumerinterface to perform operations on input values. - Understanding the
Supplierinterface to handle data provisioning.
Overview of Consumer and Supplier Interfaces
In Java, functional interfaces like Consumer and Supplier play an important role in functional programming. Both of these interfaces are marked with the @FunctionalInterface annotation, which indicates that they have exactly one abstract method. This makes them ideal for use with lambda expressions.
ConsumerInterface: Represents an operation that takes a single input argument and returns no result. It’s commonly used for operations like printing or logging, where you need to process data but don’t need to return anything.SupplierInterface: Represents a function that supplies a result without taking any input arguments. It's useful in scenarios where you need to generate or provide data on demand.
Using the Consumer Interface
The following example demonstrates how to implement a simple Consumer that prints a message to the console:
The Consumer interface allows you to define a block of code that performs operations on the received input. In this example, the printer is a consumer that prints the input message to the console. The lambda expression message -> System.out.println(message) accepts a string and prints it.
Implementing the Supplier Interface
