BiConsumer Interface is a part of the java.util.function package which is introduced in Java 8. It is an in-built Functional Interface. This function expect two arguments as input but produces no output. In this post, we are going to see several implementations of BiConsumer Interface by using different examples.

BiConsumer_Interface_Java8_Techndeck

BiConsumer Interface in Java 8 with Examples...!!! Share on X

Look at BiConsumer Javadoc description below:

BiConsumerInterface_Signature_Techndeck

 

 

 

 

 

BiConsumer Interface contains 2 methods:

  1. accept 

  2. andThen

 

Let’s discuss these methods:

accept 

This method accepts two input arguments and performs operation on the given arguments.

void accept(T t, U u);

 

Below are the several examples to demonstrate accept() method:

Example 1. with Integer

import java.util.function.BiConsumer;

public class BiConsumerInterfaceJava8Example1 {

    public static void main(String args[]) {

        System.out.println("Ex. 1 - Java 8 BiConsumer Interface\n");

        BiConsumer <Integer, Integer> biConsumerObj = (a, b) -> System.out.println(a * b);

        biConsumerObj.accept(10, 3);

    }
}

 

Example 2. with HashMap

import java.util.HashMap;
import java.util.function.BiConsumer;

public class BiConsumerInterfaceJava8Example3 {

    public static void main(String args[]) {

        System.out.println("Ex. 2 - Java 8 Consumer Interface\n");

        BiConsumer <String, HashMap <Integer,String>> biConsumerListObj = (s, map) -> {

            if (!map.containsValue(s)) {
                map.put(2, s);
            }
            System.out.println(map);

        };

        HashMap <Integer, String> hashMap = new HashMap <Integer, String> ();

        hashMap.put(1, "Isha");
        hashMap.put(3, "Noni");

        biConsumerListObj.accept("Deepak", hashMap);
    }
}

 

Example 3. with ArrayList using Stream API 

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

public class BiConsumerInterfaceJava8Example2 {

    public static void main(String args[]) {

        System.out.println("Ex. 3 - Java 8 BiConsumer Interface\n");

        BiConsumer <List<Integer> , List <Integer>> biConsumerListObj = (l1, l2) -> {

            if (!l1.equals(l2)) {
                System.out.println("Values of List 1:\n");
                l1.stream().forEach(list1Value -> System.out.print(list1Value + "\n"));

                System.out.println("\nValues of List 2:\n");
                l2.stream().forEach(list2Value -> System.out.print(list2Value + "\n"));
            }
        };

        List <Integer> sampleList1 = new ArrayList <Integer> ();

        sampleList1.add(3);
        sampleList1.add(44);
        sampleList1.add(91);

        List <Integer> sampleList2 = new ArrayList <Integer> ();

        sampleList2.add(75);
        sampleList2.add(8);

        biConsumerListObj.accept(sampleList1, sampleList2);

    }
}

 

Example 4. with custom Class object (like ‘Students’ in this case)

import java.util.function.BiConsumer;

public class BiConsumerInterfaceJava8Example4 {

    public static void main(String args[]) {

        System.out.println("Ex. 4 - Java 8 BiConsumer Interface\n");

        BiConsumer <String, Students> consumerListObj = (s, student) -> {

            if (student.getName() != s) {
                student.setName(s);
                student.setAge(5);
                System.out.println("Newly added student details: \n" + "\nName: \n" + student.getName() + "\n\nAge:\n" + student.getAge());
            } else {
                System.out.println("Student with this name already exist.");
            }
        };

        Students student = new Students(1, "Isha");

        consumerListObj.accept("Deepak", student);

    }
}

 

Students Class:

public class Students {

    int age;
    String name;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Students() {}

    public Students(int age, String name) {
        this.age = age;
        this.name = name;
    }

}

 

andThen

This method returns a composed BiConsumer that performs, in sequence, this operation followed by the after operation. If performing either operation throws an exception, it is relayed to the caller of the composed operation. If performing this operation throws an exception, the after operation will not be performed.

default BiConsumer<T, U> andThen(BiConsumer<? super T, ? super U> after) {
        Objects.requireNonNull(after);

        return (l, r) -> {
            accept(l, r);
            after.accept(l, r);
        };
    }

 

Below are the several examples to demonstrate andThen() method:

Example 5. with String

import java.util.function.BiConsumer;

public class BiConsumerInterfaceJava8Example5 {

    public static void main(String args[]) {

        System.out.println("Ex. 5 - Java 8 Consumer Interface\n");

        BiConsumer <String, String> biConsumerObj = (s1, s2) -> {

            if (s1.length() == s2.length()) {
                System.out.println("Both the strings are of equal length");
            } else {
                System.out.println("Both the strings are of unequal length");
            }
        };

        biConsumerObj.andThen(biConsumerObj).accept("justanordinarywriter.com", "techndeck.com");
    }
}

 

Example 6. with ArrayList using Stream API 

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

public class BiConsumerInterfaceJava8Example6 {

    public static void main(String args[]) {

        System.out.println("Ex. 6 - Java 8 BiConsumer Interface\n");

        //Add 10 to every integer of the list 
        BiConsumer <Integer, List <Integer>> updatedList = (i, l) -> {
            for (int j = 0; j < l.size(); j++)

                l.set(j, i + l.get(j));
        };

        //Display a list of integers 
        BiConsumer <Integer, List <Integer>> printList = (i, l) -> l.stream().forEach(a -> System.out.print(a + "\n"));

        List <Integer> list = new ArrayList <Integer> ();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(5);

        updatedList.andThen(printList).accept(10, list);
    }
}

 

Java 8 BiConsumer Interface is an absolute useful addition as part of ‘Functional Interfaces’ and can serve variety of purposes. It is quite powerful as it can be used as a higher order functions through lambda functions and above examples could help you to get better idea on how to implement it.

 

BiConsumer Interface in Java 8 with Examples...!!! Share on X

 

Do you like this Post? – then check my other helpful posts:

Other Useful References:

 

Author

  • Deepak Verma

    Deepak Verma is a Test Automation Consultant and Software development Engineer for more than 10 years. His mission is to help you become an In-demand full stack automation tester.

    He is also the founder of Techndeck, a blog and online coaching platform dedicated to helping you succeed with all the automation basics to advanced testing automation tricks.

    View all posts