Over

120,000

Worldwide

Saturday - Sunday CLOSED

Mon - Fri 8.00 - 18.00

Call us

 

Java Functional Interfaces – Consumer & BiConsumer

Java Functional InterfacesConsumer & BiConsumer

This section describes the functional interfaces Consumer & BiConsumer defined in java.util.Function package in Java 8.

What is it?

 Consumer: A functional interface that represents an operation that accepts one argument and returns no result.  

@FunctionalInterface

public interface Consumer<T>

{

       void accept(T t) ;

}

.

 BiConsumer: A functional interface that represents an operation that accepts two arguments and returns no result.  

@FunctionalInterface

public interface BiConsumer<T,U>

{

     void accept(T t, U u);

}

.

When should you use it?

.

 It is used in scenarios where some operation needs to be performed on an object without returning any result.
 The forEach() method of Iterable interfaces takes a Consumer as input and calls accept() method on each iterable object.
 The forEach() method of HashMap class takes a BiConsumer as input and performs operation of each entry of hashmap.

.

Examples

.

The examples illustrated below use the following Employee POJO class:

.

package org.examples;

.

public class Employee {

      private String name;

      private Integer hourRate;

      public String getName() {

        return name;

      }

      public void setName(String name) {

        this.name = name;

      }

      public Integer getHourRate() {

        return hourRate;

      }

      public void setHourRate(Integer hourRate) {

        this.hourRate = hourRate;

      }

      public Employee(String name, Integer hourRate) {

        super();

        this.name = name;

        this.hourRate = hourRate;

      }

                   @Override

      public String toString() {

        return “Employee [name=” + name + “, hourRate=” + hourRate + “]”;

      }

}

.

.

 Consumer

.

1.This implementation shows simple usage of Consumer function to print the name and rate of employees in a particular format, from a list of Employee objects.

package org.examples;

.

package org.examples;

.

import java.util.Arrays;

import java.util.List;

import java.util.function.Consumer;

.

public class ConsumerExample1 {

  public static void main(String[] args)

  {

     List<Employee> employees = Arrays.asList(new Employee(“Jack”, 10),

            new Employee(“Robert”, 50),

        new Employee(“David”, 30),

        new Employee(“Abhi”, 20));  

    employeeConsumer(employees, print());  

              

       }

  

  public static Consumer<Employee> print()

  {

    Consumer<Employee> consumer = emp ->

                    System.out.println(“Rate of “ + emp.getName() + ” is $” +

                                                    emp.getHourRate() + ” per hour.”);

    return consumer;

  }

       

      public static void employeeConsumer

(List<Employee> employees, Consumer<Employee> consumer)

  {

    for(Employee emp : employees)

    {

      consumer.accept(emp);

    }

  }

}

.

Output:

Rate of Jack is $10 per hour.

Rate of Robert is $50 per hour.

Rate of David is $30 per hour.

Rate of Abhi is $20 per hour.

.

.

2.This implementations shows usage of Consumer function from previous example in forEach() method.

.

.

package org.examples;

.

package org.examples;

.

import java.util.Arrays;

import java.util.List;

import java.util.function.Consumer;

.

public class ConsumerExample2 {

  public static void main(String[] args)

  {

     List<Employee> employees = Arrays.asList(new Employee(“Jack”, 10),

            new Employee(“Robert”, 50),

        new Employee(“David”, 30),

        new Employee(“Abhi”, 20));  

    employees.forEach(print());  

       }

  

  public static Consumer<Employee> print()

  {

    Consumer<Employee> consumer = emp ->

                    System.out.println(“Rate of “ + emp.getName() + ” is $” +

                                                    emp.getHourRate() + ” per hour.”);

    return consumer;

  }

}

.

Output:

Rate of Jack is $10 per hour.

Rate of Robert is $50 per hour.

Rate of David is $30 per hour.

Rate of Abhi is $20 per hour.

.

.

3.This implementation shows chaining of two Consumer functions using andThen() method. It converts the name of each employee to upper case and then prints it, from a list of Employee objects.

package org.examples;

.

import java.util.Arrays;

import java.util.List;

import java.util.function.Consumer;

.

public class ConsumerExample3 {

    public static void main(String[] args)

  {

     List<Employee> employees = Arrays.asList(new Employee(“Jack”, 10),

            new Employee(“Robert”, 50),

        new Employee(“David”, 30),

        new Employee(“Abhi”, 20));  

    employeeConsumer(employees, changeNameCase(), print());

.

            //Alternative method-use forEach with the consumer as input

    employees.forEach(changeNameCase().andThen(print()));

.

  }

  

  public static Consumer<Employee> print()

  {

    Consumer<Employee> consumer = emp -> System.out.println(emp.getName());

    return consumer;

  }

  

  public static Consumer<Employee> changeNameCase()

  {

     Consumer<Employee> consumer = emp ->

                                            emp.setName(emp.getName().toUpperCase());

     return consumer;

  }

  

  public static void employeeConsumer(List<Employee> employees, Consumer<Employee>

                                              consumer1, Consumer<Employee> consumer2)

  {

    for(Employee emp : employees)

    {

      consumer1.andThen(consumer2).accept(emp);

    }

  }

}

Output:

JACK

ROBERT

DAVID

ABHI

.

.

.

.

 BiConsumer

.

1.This implementation shows usage of BiConsumer function to append last name in the name of each employee in a list of Employee objects.

package org.examples;

.

import java.util.Arrays;

import java.util.List;

import java.util.function.BiConsumer;

.

public class BiConsumerExample1 {

  public static void main(String[] args)

  {

     List<Employee> employees = Arrays.asList(new Employee(“Jack”, 10),

            new Employee(“Robert”, 50),

        new Employee(“David”, 30),

        new Employee(“Abhi”, 20));  

    

    appendLastName().accept(employees.get(0),“Fernandez”);

    appendLastName().accept(employees.get(1),“Jones”);

    appendLastName().accept(employees.get(2),“Beckham”);

    appendLastName().accept(employees.get(3),“San”);

    System.out.print(employees);

  }

    

  public static BiConsumer<Employee,String> appendLastName()

  {

    BiConsumer<Employee,String> consumer = (emp,str) ->

                                                  emp.setName(emp.getName()+” “+str);

    return consumer;

  }

}

Output:

[Employee [name=Jack Fernandez, hourRate=10], Employee [name=Robert Jones, hourRate=50], Employee [name=David Beckham, hourRate=30], Employee [name=Abhi San, hourRate=20]]

.

.

2.This implementation shows usage of BiConsumer function in forEach() method of HashMap. It iterates a hashmap with department as key and list of employees as value, and prints the total hourRate of each department.

.

package org.examples;

.

import java.util.Arrays;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import java.util.function.BiConsumer;

.

public class BiConsumerExample2 {

  public static void main(String[] args)

  {

    Map<String,List<Employee>> employees = new HashMap<>();

    employees.put(“Admin”,

                   Arrays.asList(new Employee(“Jack”, 10),new Employee(“David”, 30)));

    employees.put(“Sales”,

                  Arrays.asList(new Employee(“Robert”, 50),new Employee(“Abhi”, 20)));

    employees.forEach(totalRate());

  }

      

  public static BiConsumer<String,List<Employee>> totalRate()

  {

    BiConsumer<String,List<Employee>> consumer = (str,list) ->

              {

                Integer total = 0;

                            for(Employee emp : list)

                {

                         total+=emp.getHourRate();

                }

              System.out.println(str + “=” + total);  

              };

    return consumer;

  }

}

Output:

Sales=70

Admin=40

.

.

3.This implementation shows a generic method that takes as input a BiConsumer function to perform operation on two Employee objects.

.

package org.examples;

.

import java.util.Arrays;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import java.util.function.BiConsumer;

.

.

import java.util.Arrays;

import java.util.List;

import java.util.function.BiConsumer;

.

public class BiConsumerExample3 {

  public static void main(String[] args)

  {

     List<Employee> employees = Arrays.asList(new Employee(“Jack”, 10),

            new Employee(“Robert”, 50),

        new Employee(“David”, 30),

        new Employee(“Abhi”, 20));  

  

     empConsumer(employees.get(0),employees.get(1), printMaxRate());

     empConsumer(employees.get(0),employees.get(1), printTotalRate());

  }

  

  public static BiConsumer<Employee,Employee> printTotalRate()

  {

    BiConsumer<Employee,Employee> consumer = (emp1,emp2) ->

    {

        Integer total = emp1.getHourRate()+emp2.getHourRate();

        System.out.println(“Total Rate=”+total);

    };

    return consumer;

  }

  

  public static BiConsumer<Employee,Employee> printMaxRate()

  {

    BiConsumer<Employee,Employee> consumer = (emp1,emp2) ->

    {

      if (emp1.getHourRate() > emp2.getHourRate()) {

        System.out.println(“Max rate=”+emp1.getHourRate());

      } else {

        System.out.println(“Max rate=”+emp2.getHourRate());

      }

    };

    return consumer;

  }

  

  public static void empConsumer(Employee emp1, Employee emp2,

                                             BiConsumer<Employee,Employee> consumer)

  {

    consumer.accept(emp1, emp2);

  }

}

Output:

Max rate=50

Total Rate=60

.

Leave a Reply

Your email address will not be published. Required fields are marked *

Working Hours

  • Monday 9am - 6pm
  • Tuesday 9am - 6pm
  • Wednesday 9am - 6pm
  • Thursday 9am - 6pm
  • Friday 9am - 6pm
  • Saturday Closed
  • Sunday Closed