How could I put a function containing multiple parameters into hashmap value in Java?

Viewed 60

I have tried to make it successful but I couldn't deal with it even though I've searched many things which is related to this problem on the internet and Stackoverflow.

So what I would like to do is like this.

    BiFunction<Integer, Integer, Integer> mul = (a, b) -> a * b;

    Map<Character, IntUnaryOperator> commands = new HashMap<>();
    commands.put('*', (a, b) -> mul.apply(a, b) );

? // commands.put('*', (a, b) ->{ return a * b;} ); <- Using lambda was impossible as well.

I would like to put a function, 'mul' into the value of hashmap, including recieveing two parmeters. I've just started using Java and I tried to check and read documents but I couldn't find out the way to do this successfully.

I'd be glad if you could help me. Thank you.

1 Answers

I would use a functional interface for this purpose.

import java.util.*;

interface Eval {
   int eval(int a, int b);
}

public class Main
{
    public static void main(String[] args) {
        Map<Character, Eval> f = new HashMap<>();
        f.put('*', (a,b)->a*b);
        f.put('+', (a,b)->a+b);
        
        System.out.println(f.get('*').eval(4,5));
        System.out.println(f.get('+').eval(4,5));
    }
}

Output

20
9
Related