Java Consumer

Introduction

In Java, the Consumer interface is a functional interface that represents an operation that accepts a single input argument and returns no result. It is part of the java.util.function package and is commonly used for operations like printing or modifying an object.

Table of Contents

  1. What is Consumer?
  2. Methods and Syntax
  3. Examples of Consumer
  4. Real-World Use Case
  5. Conclusion

1. What is Consumer?

Consumer is a functional interface that performs an operation on a given input. It is often used in lambda expressions and method references.

2. Methods and Syntax

The main method in the Consumer interface is:

  • void accept(T t): Performs this operation on the given argument.

Syntax

Consumer<T> consumer = (T t) -> {
    // operation on t
};

3. Examples of Consumer

Example 1: Printing a Value

import java.util.function.Consumer;

public class ConsumerExample {
    public static void main(String[] args) {
        // Define a Consumer that prints a string
        Consumer<String> print = (str) -> System.out.println(str);

        print.accept("Hello, World!");
    }
}

Output:

Hello, World!

Example 2: Modifying an Object

import java.util.function.Consumer;

public class ModifyExample {
    public static void main(String[] args) {
        // Define a Consumer that appends a suffix to a string
        Consumer<StringBuilder> addSuffix = (sb) -> sb.append(" is awesome!");

        StringBuilder message = new StringBuilder("Java");

        addSuffix.accept(message);

        System.out.println(message);
    }
}

Output:

Java is awesome!

4. Real-World Use Case: Logging Information

In applications, Consumer can be used to log information about various processes or data.

import java.util.function.Consumer;

public class Logger {
    public static void main(String[] args) {
        // Define a Consumer to log messages
        Consumer<String> log = (message) -> System.out.println("Log: " + message);

        log.accept("Application started.");
        log.accept("Processing data...");
        log.accept("Application finished.");
    }
}

Output:

Log: Application started.
Log: Processing data...
Log: Application finished.

Conclusion

The Consumer interface is a versatile tool in Java for performing operations on a single input argument without returning a result. It simplifies operations like printing, modifying objects, or logging, making it a valuable component in functional programming. Using Consumer can enhance code clarity and maintainability.

Comments