0

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);
  • Seems like the solution would be the same as in the Q&A you linked, just with `BiFunction` instead of `Function` (maybe also with a `BiConsumer`?). Is there a specific problem you're having with adapting the code? – Slaw Oct 19 '22 at 04:35
  • I want to write a Generic Methods that implements the combined use of BiFuncton and Consumer – bootstrap2025 Oct 19 '22 at 06:53
  • 3
    You can not compose a `BiFunction` and `Consumer` to a `Consumer`. The former expects *two* arguments, hence, the result has to be a `BiConsumer`. Besides that, if you want “to write a Generic Method”, then do it. As Slaw said, you can use the Q&A you already linked and adapt it. Feel free to ask questions about your actual attempt, if you struggle. – Holger Oct 19 '22 at 06:56

1 Answers1

0

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);
Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69