如何在Java中将包含多个参数的函数放入hashmap值中



我试图让它成功,但我无法处理它,尽管我在互联网和Stackoverflow上搜索了许多与此问题有关的东西。

所以我想做的就是这样。

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;}(<-使用lambda也是不可能的。

我想在hashmap的值中放入一个函数"mul",包括接收两平方米。我刚开始使用Java,我试着检查和阅读文档,但我找不到成功的方法。

如果你能帮助我,我会很高兴的。非常感谢。

我会为此使用函数接口。

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));
}
}

输出

20
9

最新更新