HomeCore JavaA guide to Java BiConsumer + Examples

A guide to Java BiConsumer + Examples

Java BiConsumer is a built-in Functional interface in java, represents an operation that accepts two input arguments and returns no result. This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference. BiConsumer functional method is accept(Object, Object).

One of the most commonly used use case for BiConsumer is forEach method of Map implementations. Java forEach method takes BiConsumer as argument.

1. Java BiConsumer methods and Examples

  1. void accept(T t, U u) – Accepts two input arguments and performs operation on the given arguments and return nothing.
  2. default BiConsumer andThen(BiConsumer after) – 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.

1.1. BiConsumer example 1

public class BiConsumerDemo {

	public static void main(String[] args) {

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

		// Very basic usage of BiFunction accept
		c1.accept(10, 20); // prints 30

		BiConsumer<String, String> c2 = (s1, s2) -> System.out.println(s1.contains(s2));

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

		// c1.andThen(c2); can not apply incompatible types Integer and String
		c1.andThen(c3).accept(5, 10); // 15 50

		// Above line eualant to following code
		c1.accept(5, 10);
		c3.accept(5, 10);
	}
}

Output :

30
15
50
15
50

1.2. BiConsumer Example 2

Following example demonstrates how to use BiConsumer to the java foraEach method.

public class BiConsumerIterateMapDemo {
    
    public static void main(String[] args) {
         
    	Map<Integer, String> m = new HashMap<>();
		m.put(1, "Peter");
		m.put(2, "Mike");
		m.put(3, "John");
		m.put(4, "Mike");
		m.put(5, "Peter");
		m.put(6, "Anand");
		m.put(7, "Peter");
		
		
		BiConsumer<Integer, String> f =
				(key, value) -> System.out.println("[Key="+key+", "+value+")]");
		
		m.forEach(f);
		
		System.out.println("---- Simplified -----");
		// following is simplified code for above code 
		m.forEach((k,v) -> System.out.println("[Key="+k+", "+v+")]"));
    }
}

Output :

[Key=1, Peter)]
[Key=2, Mike)]
[Key=3, John)]
[Key=4, Mike)]
[Key=5, Peter)]
[Key=6, Anand)]
[Key=7, Peter)]
---- Simplified -----
[Key=1, Peter)]
[Key=2, Mike)]
[Key=3, John)]
[Key=4, Mike)]
[Key=5, Peter)]
[Key=6, Anand)]
[Key=7, Peter)]

References

  1. Java documentation
  2. Java Consumer interface
  3. Java HashMap examples
  4. java forEach method

LEAVE A REPLY

Please enter your comment!
Please enter your name here