Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method reference in Java unil BiFunction

I have question about passing method reference as argument in java (util) functions.

I have two functions

Function<Value, Output> f1 = (val) -> {
    Output o = new Output();
    o.setAAA(val);
    return o;
};

Function<Value, Output> f2 = (val) -> {
    Output o = new Output();
    o.setBBB(val);
    return o;
};

I want to merge them into one function which should looked like

BiFunction<MethodRefrence, Value, Output> f3 = (ref, val) -> {
    Output o = new Output();
    Output."use method based on method reference"(val);
    return o;
};

I want to use this function like

f3.apply(Output::AAA, number);

Is it possible ? I can't figure out correct syntax, how to make such a function.

like image 514
jmt Avatar asked Jan 06 '23 18:01

jmt


1 Answers

It looks like you want a function like

BiFunction<BiConsumer<Output,Value>, Value, Output> f = (func, val) -> {
    Output o = new Output();
    func.accept(o, val);
    return o;
};

which you can invoke like

f.apply(Output::setAAA, val);
f.apply(Output::setBBB, val);
like image 114
Holger Avatar answered Jan 16 '23 06:01

Holger