December 10, 2018

How to use java.util.function.Consumer functional interface in java – And different implementations using class, lambdas and method reference

Consumer is present in java.util.functions  package. It is a Functional Interface .

In this article, we will use different ways to provide implementations for this interface.

The Consumer implementation will take a String-input  and write it to console. The System.out.println  method can be replaced with other writers, like it can modified to write the contents to a file or server etc.

Method 1 :- Implement the Consumer interface using a Regular Class.

package com.functionalinterface;

import java.util.function.Consumer;

public class ConsumerImplementor implements Consumer<String> {
    @Override
    public void accept(String word) {
        System.out.println(word);
    }
}

This is a normal implementation, where we implement an interface to provide concrete implementation for the abstract methods.

Method 2 :- anonymous class

Consumer<String> printByAnonymousClass = new Consumer<String>() {
    @Override
     public void accept(String word) {
            System.out.print(word);
    }
};

In the above code snippet, we provide an implementation for the interface in anonymous class way. We all have seen code like this in old java code.

Method 3 :- Lambdas

Consumer<String> printByLambdaDynamic = (word) -> System.out.println(word);

So, this is the first use of Java 8 here 🙂
We are using lambdas . Here, we create a lambda which takes one input of String  type and returns nothing.  This implementation is as per definition of accept method in Consumer interface.

Consumer<String> printByLambaStatic = (String word) -> System.out.print(word);

We can specify the data-type of parameter in the lambda, it is not necessary but you can do it.

Method 4 : Method Reference

Consumer<String> printByMethodReference = System.out::println;

We can also use method reference to provide the implementation of accept  method.
Here, we are using println function, which takes one input  and returns nothing. As, the declaration of both of the methods, println  and accept, are the same. We can use println  to provide implementation for accept method.