Java BiConsumer Functional Interface Tutorial

Overview

The BiConsumer is a part of the java.util.function package. As the name suggest, this interface is a Consumer. That means it takes input arguments and returns void.

Practical use cases

This interface can be useful in various cases, for example, it can be used to create side effects like modifying state, printing, or logging.

BiConsumer Examples

Java

Here, I created a BiConsumer and provided the implementation method to the abstract method named accept.

Using the consumer is quite straightforward:

Using BiConsumer in stream

Using the BiConsumer above, let’s see how you can use it in a stream:

Java

The function above print the name of the cities and their length.

You can also write methods that has a BiConsumer as a paramenter.

Consider you are building a system that log users’ login activities with the following data model:

Java

You can create BiConsumer to log the activities as below:

Java

Now you can either create the consumers and pass into the methods or you can use lambda expressions for brevity (and coolness 😎)

Java

The result would be like this:

Using BiConsumer for logging

Conclusion

In this post, I’ve shown you how to use BiConsumer in Java.

Leave a Comment