Java : BiFunction with Examples
BiFunction (Java SE 18 & JDK 18) API Examples.
You will find code examples on most BiFunction methods.
Summary
final var func = new BiFunction<Integer, Double, String>() {
@Override
public String apply(Integer i, Double d) {
return "%d : %f".formatted(i, d);
}
};
final var ret = func.apply(123, 0.456);
System.out.println(ret); // 123 : 0.456000
final var map = new HashMap<String, Integer>();
map.put("a", 1);
map.put("b", 2);
System.out.println(map); // {a=1, b=2}
final BiFunction<String, Integer, Integer> func
= (key, value) -> "a".equals(key) ? value * 10 : value * 100;
map.compute("a", func);
System.out.println(map); // {a=10, b=2}
map.compute("b", func);
System.out.println(map); // {a=10, b=200}
Methods
default <V> BiFunction<T,U,V> andThen (Function<? super R,? extends V> after)
final var func1 = new BiFunction<Integer, Double, String>() {
@Override
public String apply(Integer i, Double d) {
return "%d : %f".formatted(i, d);
}
};
final var after = new Function<String, String>() {
@Override
public String apply(String str) {
return str + " ... andThen!";
}
};
System.out.println(func1.apply(123, 0.456)); // 123 : 0.456000
final var func2 = func1.andThen(after);
System.out.println(func2.apply(123, 0.456)); // 123 : 0.456000 ... andThen!
R apply (T t, U u)
final var func = new BiFunction<Integer, Double, String>() {
@Override
public String apply(Integer i, Double d) {
return "%d : %f".formatted(i, d);
}
};
final var ret = func.apply(123, 0.456);
System.out.println(ret); // 123 : 0.456000