Member-only story
Java 8 Functional Interfaces and Their Use Cases: A Comprehensive Guide for Developers
5 min readOct 7, 2024
1. Consumer Interface
The Consumer
interface represents an operation that takes a single input and performs an action on it without returning any result. It’s a perfect choice when we need to consume or perform side effects like logging or modifying objects.
Key Method:
void accept(T t)
: Takes a single input parameter of typeT
and performs some operation on it.
Syntax of the Consumer Interface
@FunctionalInterface
public interface Consumer<T> {
void accept(T t);
}
Usage Example of the Consumer Interface
Let’s see how to use the Consumer
interface with an example.
import java.util.function.Consumer;
public class ConsumerExample {
public static void main(String[] args) {
// Creating a Consumer to print the value
Consumer<String> printConsumer = s -> System.out.println("Consumed value: " + s);
// Applying the Consumer
printConsumer.accept("Hello, World!"); // Output: Consumed value: Hello, World!
}
}
In this example, the Consumer
takes a String
and simply prints it.