BiConsumer Interface – Example

BiConsumer is a functional interface which represents an operation that accepts two input arguments and returns no result.

Lets see how we can use BiConsumer interface with an example.

``````
import java.util.function.BiConsumer;

public class BiConsumerExample {

public static void main(String[] args) {

BiConsumer addConsumer = (x, y) -> {
};

BiConsumer subtractConsumer = (x, y) -> {
System.out.println("Subtract Operation result:" + (x - y));
};

BiConsumer divideConsumer = (x, y) -> {
System.out.println("Divide Operation result:" + (x / y));
};

BiConsumer multiplyConsumer = (x, y) -> {
System.out.println("Multiply Operation result:" + (x * y));
};
.andThen(subtractConsumer)
.andThen(divideConsumer)
.andThen(multiplyConsumer)
.accept(10, 5);
}

}
```
```

In the above program, we have defined 4 BiConsumer operations and each one takes two integer values as input and perform appropriate arithmetic operation and prints the result.

We can chain all these operations with andThen() method.

The output of the above program is given below.

``````

Subtract Operation result:5
Divide Operation result:2
Multiply Operation result:50

```
```

If an error occurs in any one of the operation, then the next operation would not be executed. For example, if you pass 10, 0 then java.lang.ArithmeticException would happen in the divide operation so it will not execute the multiply operation.

Refer below the code and its response.

``````
import java.util.function.BiConsumer;

public class BiConsumerExample {

public static void main(String[] args) {

BiConsumer addConsumer = (x, y) -> {
};

BiConsumer subtractConsumer = (x, y) -> {
System.out.println("Subtract Operation result:" + (x - y));
};

BiConsumer divideConsumer = (x, y) -> {
System.out.println("Divide Operation result:" + (x / y));
};

BiConsumer multiplyConsumer = (x, y) -> {
System.out.println("Multiply Operation result:" + (x * y));
};
.andThen(subtractConsumer)
.andThen(divideConsumer)
.andThen(multiplyConsumer)
.accept(10, 0);
}

}
```
```
``````