Java 8 Consumer Examples

The Consumer functional interface in Java 8 is used when we want to define a single argument operation that performs an action without returning any result. It represents an operation that takes an input and processes it.

The main feature of a Consumer functional interface is that it doesn’t return anything. It just consumes the input and performs some action. This is how the Consumer interface is internally defined.

@FunctionalInterface
public interface Consumer<T> {
    void accept(T t);//Performs some operation for the given argument T

    default Consumer<T> andThen(Consumer<? super T> after) {
        Objects.requireNonNull(after);
        return (T t) -> { accept(t); after.accept(t); };
    }

Let’s see different examples that demonstrate how to use Consumer interface.

1. Printing Elements of a List.

The Consumerinterface is often used with collection processing methods like forEach to perform an action on each element of the collection.

import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;

public class ListConsumerExample {
    public static void main(String[] args) {
        List<String> fruits = Arrays.asList("Apple", "Banana", "Orange", "Mango");

        Consumer<String> printConsumer = fruit -> System.out.println(fruit);

        fruits.forEach(printConsumer);
    }
}

Output:-

Apple
Banana
Orange
Mango

Here, the Consumer is used to print each element of the list without modifying it. The lambda expression within the forEach method defines the action to be taken on each element.

2. Modifying Elements of a Collection

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

public class CollectionConsumerExample {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>();
        names.add("Alice");
        names.add("Bob");
        names.add("Charlie");

        Consumer<String> addPrefixConsumer = name -> {
            String modifiedName = "Mr. " + name;
            names.set(names.indexOf(name), modifiedName);
        };

        names.forEach(addPrefixConsumer);

        System.out.println(names);
    }
}

Output:-

[Mr. Alice, Mr. Bob, Mr. Charlie]

In this example, the Consumer modifies each element of the list by adding a prefix (“Mr. “) to it. The forEach loop applies the consumer’s action to each element.

3. Logging

import java.util.function.Consumer;

public class LoggingConsumerExample {
    public static void main(String[] args) {
        Consumer<String> logConsumer = message -> System.out.println("Logging: " + message);

        logConsumer.accept("This is a log message.");
    }
}

Output:-

Logging: This is a log message.

Here, the Consumer is used to log a message. The accept method invokes the consumer’s action on the provided argument.

4. Updating Database Records

import java.util.function.Consumer;

class DatabaseRecord {
    private String data;

    public DatabaseRecord(String data) {
        this.data = data;
    }

    public String getData() {
        return data;
    }

    public void updateData(Consumer<String> updateFunction) {
        updateFunction.accept(data);
    }
}

public class DatabaseUpdateConsumerExample {
    public static void main(String[] args) {
        DatabaseRecord record = new DatabaseRecord("Initial data");

        Consumer<String> updater = newData -> record.updateData(data -> data = newData);

        updater.accept("Updated data");

        System.out.println(record.getData());
    }
}

Output:-

Updated data

Explanation: In this example, the Consumer is used to update the data of a DatabaseRecord object. The updateData method of the DatabaseRecord class accepts a Consumer that defines how to update the data.

5. Sending Notifications

import java.util.function.Consumer;

class NotificationService {
    public static void sendNotification(String message) {
        System.out.println("Sending notification: " + message);
    }
}

public class NotificationConsumerExample {
    public static void main(String[] args) {
        Consumer<String> notificationConsumer = NotificationService::sendNotification;

        notificationConsumer.accept("Hello, world!");
    }
}

Output:-

Sending notification: Hello, world!

In this example, the Consumer is used to send a notification using the NotificationService. The accept() method invokes the method reference, which is equivalent to calling NotificationService.sendNotification(message).

Note – In all of these examples, the Consumer functional interface is used to define an action or operation that is performed on the input without returning a result. It’s a versatile tool for scenarios where you need to process, transform, or perform an operation on data.

Five objective questions related to the Consumer interface in Java 8:

Question 1:
Which package contains the Consumer interface in Java 8?
a) java.lang
b) java.util.function
c) java.util
d) java.consumer

Question 2:
What is the purpose of the Consumer interface in Java?
a) It represents a function that takes two arguments and produces a result.
b) It represents a function that takes one argument and produces a result.
c) It represents a function that takes one argument and performs an action without returning a result.
d) It represents a function that takes two arguments and performs an action without returning a result.

Question 3:
Which method of the Consumer interface is used to execute the consumer’s action on the given input?
a) run()
b) execute()
c) accept()
d) apply()

Question 4:
Which of the following code snippets demonstrates the correct usage of a Consumer to print each element of a list?
a)

Consumer<String> printConsumer = item -> System.out.print(item);
List<String> items = Arrays.asList("A", "B", "C");
items.forEach(printConsumer);

b)

Consumer<String> printConsumer = item -> System.out.println(item);
List<String> items = Arrays.asList("A", "B", "C");
items.printEach(printConsumer);

c)

Consumer<String> printConsumer = item -> System.out.println(item);
List<String> items = Arrays.asList("A", "B", "C");
items.forEach(printConsumer.accept(item));

d)

Consumer<String> printConsumer = item -> System.out.println(item);
List<String> items = Arrays.asList("A", "B", "C");
items.apply(printConsumer);

Question 5:
Which of the following statements about the andThen method of the Consumer interface is true?
a) It returns a new Consumer that performs the same action as the original Consumer.
b) It executes two Consumer actions in parallel.
c) It returns a new Consumer that first performs the action of the original Consumer, and then the action of the provided Consumer.
d) It merges two Consumer actions into a single action.

Answers

  1. b) java.util.function
  2. c) It represents a function that takes one argument and performs an action without returning a result.
  3. c) accept()
  4. a)
  5. c) It returns a new Consumer that first performs the action of the original Consumer, and then the action of the provided Consumer.

Other Java 8 examples.

See docs.

That’s all about Java 8 Consumer Examples.