Java : BiFunction with Examples

BiFunction (Java SE 18 & JDK 18) API Examples.
You will find code examples on most BiFunction methods.


Summary

Represents a function that accepts two arguments and produces a result. This is the two-arity specialization of Function.

Class diagram

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)

Returns a composed function that first applies this function to its input, and then applies the after function to the result.

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)

Applies this function to the given arguments.

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

Related posts

To top of page