Composing a Java BiFunction and Consumer

312 Views Asked by At

Similar to this question Composing a Java Function and Consumer. What is the best way to functionally compose a java BiFunction and a Consumer? For example given some BiFunction<String, String,String> f and some Consumer c then doing f.andThen(c) ?

BiFunction<String, String, String> a = (a,b)->{return a+b;}
Consumer<String> b = x -> System.out.println(x);
Consumer<String> composed = a.andThen(b);
1

There are 1 best solutions below

0
Jean-Baptiste Yunès On

You can only compose BiFunctions with Functions. Then you may create a Function returning Void and get with a composition a BiFunction in return:

BiFunction<String, String, String> a = (x,y)->{return x+y;};
Function<String,Void> b = x -> { System.out.println(x); return null; };
BiFunction<String,String,Void> f = a.andThen(b);
f.apply("foo","bar");

which will give you:

foobar

Function<...,Void> are slightly tricky as Java generics can only be instanciated with classes, not with primitive types as void is. You then need to return a Void object reference, but this type cannot be instanciated and the only value you can use is null.

At the end if you need a BiConsumer you can build it like this:

BiConsumer<String,String> c = (x,y) -> f.apply(x,y);