Learnitweb

BiConsumer interface in Java

BiConsumer interface was introduced in Java 8. This interface is available in java.util.function package.

BiConsumer represents an operation that accepts two arguments and return no result. BiConsumer is similar to the Consumer interface with the difference that BiFunction accepts two arguments whereas Consumer accepts only one.

BiConsumer is expected to process the data and thus expected to operate via side-effects.

@FunctionalInterface
public interface BiConsumer<T, U> {
  void accept(T t, U u);
}

Methods of BiConsumer interface

void accept(T t, U u)Performs this operation on the given arguments.
default BiConsumer andThen(BiConsumer after)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.

BiConsumer example 1

import java.util.function.BiConsumer;

public class BiConsumerExample {
	public static void main(String[] args) {
		//BiConsumer to accept and concatenate two strings
		BiConsumer<String, String> biConsumer = (x, y) -> System.out.println(x + y);
		biConsumer.accept("hello ", "world"); 
	}
}

Output

Hello World

BiConsumer example 2

import java.util.function.BiConsumer;

public class BiConsumerExample {
	public static void main(String[] args) {
		//BiConsumer to add two numbers
		BiConsumer<Integer, Integer> addition = (a, b) -> {
			System.out.println(a + b);
		};
		
		//BiConsumer to subtract two numbers
		BiConsumer<Integer, Integer> subtraction = (a, b) -> {
			System.out.println(a - b);
		};
		// Using andThen()
		addition.andThen(subtraction).accept(10, 20);
	}
}

Output

30
-10