Search code examples
javalambdafunctional-interface

How to add BiFunction on a MAP properly


private static final Map<String, BiFunction<String, Player, Player>> SELF_FUNCTION = Map.of
(
    "pAtk", BiFunction<Integer, Player, Player> pAtk = (k, v) -> k.getPAtk(v),
    "mAtk", BiFunction<Integer, Player, Player> mAtk = (k, v) -> k.getMAtk(v),
);

I can't manage to make this code to be working. I want to do a for entry and get the Key and calculate the stat is given by BiFunction but i can't make it work.


Solution

  • In BiFunction<T, U, R> definition T is the type of the first argument, U is the type of the second argument, R is the return type.

    Thus, providing that class Player contains methods Player getPAtk(String v) and Player getMAtk(String v), the map of BiFunction<Player, String, Player> can be created as:

    private static final Map<String, BiFunction<Player, String, Player>> SELF_FUNCTION = Map.of (
            "pAtk", (player, value) -> player.getPAtk(value), // or Player::getPAtk
            "mAtk", (player, value) -> player.getMAtk(value) // or Player::getMAtk
    );
    

    or switch the arguments in the lambda to match BiFunction definition:

    private static final Map<String, BiFunction<String, Player, Player>> SELF_FUNCTION = Map.of (
            "pAtk", (value, player) -> player.getPAtk(value),
            "mAtk", (value, player) -> player.getMAtk(value)
    );