What is the Consumer in a lambda function?

wagnernegrao

Wagner Negrão 👨‍🔧

Posted on July 9, 2021

What is the Consumer in a lambda function?

Well, this can seem well consolidated in the community but I think it important to create something about this and help me learn more.

Initially, we will create the example code.

Car car1 = new Car("Porsche 911");
Car car2 = new Car("Ferrari 458");
Car car3 = new Car("Lamborghini Urus");

List<Car> cars = Arrays.asList(car1, car2, car3);

cars.forEach( (c) -> System.out.println(c.getName));
Enter fullscreen mode Exit fullscreen mode

To explain the Consumer interface I will use the method forEach().

Since Java 8, we have a function lambda that receives an Interface function that stays responsible to organise this iteration that will occur. To execute a function lambda we have to have an Interface function to accomplish the action.

In the case we have the Interface function Consumer is part of the package Function of java and allows use with a function.

To stay more clear we will create a class anonymous that implements a class Consumer.


Consumer<Car> show = new Consumer<Car>() {
    public void accept(Car c) {
        System.out.println(c.getName);
    }
}

cars.forEach(show);
Enter fullscreen mode Exit fullscreen mode

The Consumer class has a unique method called Accept that stays responsible to receive the function that receives a value that will be consumed with some action, but not returns anything. This way of presenting the function is not conventional, but he introduces what occurs when using a function lambda, for example, to understand what occurs when creating a function. Now we will refactor this code.


cars.forEach( (c) -> System.out.println(c.getName));

Enter fullscreen mode Exit fullscreen mode

We can see in that refactoring as in the first example, not we initialize the object C this occurs because the compiler understands that we assigning a Consumer thus abstracting this information, between having -> that is an identifier of a function lambda, another point is that not have the method Accept he is inferred during the process of compilation, then the method forEach receive a Consumer and send an action to be executed with each iteration. So we briefly understand how the functional interface works by streams in Java.

💖 💪 🙅 🚩
wagnernegrao
Wagner Negrão 👨‍🔧

Posted on July 9, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related