Close

Java 8 Functional Interfaces - BiConsumer.andThen() Examples

Java 8 Functional Interfaces Java Java API 


Interface:

java.util.function.BiConsumer

java.util.function.BiConsumerBiConsumerLogicBig

Method:

default BiConsumer<T,U> andThen(BiConsumer<? super T,? super U> after)

Returns a composed BiConsumer that performs, in sequence, this operation followed by the after operation.


Examples


package com.logicbig.example.biconsumer;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiConsumer;

public class AndThenExample {

public static void main(String... args) {
BiConsumer<AtomicInteger, Integer> setter = AtomicInteger::set;
BiConsumer<AtomicInteger, Integer> adder = AtomicInteger::getAndAdd;
BiConsumer<AtomicInteger, Integer> biConsumer = setter.andThen(adder);
AtomicInteger ai = new AtomicInteger();
biConsumer.accept(ai, 4);
System.out.println(ai);
}
}

Output

8




package com.logicbig.example.biconsumer;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Map;
import java.util.function.BiConsumer;

public class AndThenExample3 {

public static void main(String... args) {
BiConsumer<Integer, Double> bc = (i, d) -> System.out.printf("integer: %s, double: %s%n", i, d);
BiConsumer<Integer, Double> bc2 = (i, d) -> {
BigDecimal sumInBigDecimal = BigDecimal.valueOf(d).add(
BigDecimal.valueOf(i)).setScale(2, RoundingMode.CEILING);
System.out.println("sum: " + sumInBigDecimal);
};
Map.of(1, 3.33d, 2, 4.934d, 3, 7.3232d).forEach(bc.andThen(bc2));
}
}

Output

integer: 2, double: 4.934
sum: 6.94
integer: 3, double: 7.3232
sum: 10.33
integer: 1, double: 3.33
sum: 4.33




See Also