Method reference in Java unil BiFunction

I have a question about passing a method reference as an 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 combine them into one function, which should look 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, for example

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

Is it possible? I can not understand the correct syntax of how to make such a function.

+4
source share
2 answers

It looks like you need 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 call as

f.apply(Output::setAAA, val);
f.apply(Output::setBBB, val);
+9
source

I'm not quite sure what you mean with a "method reference", but I think you want something like this:

BiFunction<Integer, Value, Output> f3 = (ref, val> -> {
    switch(ref) {
        case 1: return f1.apply(value);
        case 2: return f2.apply(value);
        default: throw new IllegalArgumentException("invalid index");
    }
}

Integer , switch, , if/else.

0

Source: https://habr.com/ru/post/1626405/


All Articles