gpt4 book ai didi

java - 将参数传递给 HashMap 值中的函数

转载 作者:行者123 更新时间:2023-11-30 06:05:19 25 4
gpt4 key购买 nike

我有一个场景,我调用 HashMap 值中存在的函数,如下所示,

  Map<Character, IntSupplier> commands = new HashMap<>();

// Populate commands map
int number=10;
commands.put('h', () -> funtion1(number) );
commands.put('t', () -> funtion1(number) );

// Invoke some command
char cmd = 'h';
IntSupplier result= commands.get(cmd); //How can I pass a parameter over here?

System.out.println(" Return value is "+result.getAsInt());

我的问题是,在获取 HashMap 值时,即使用commands.get(cmd)时,我可以将参数传递给函数(function1)吗?

谢谢。

最佳答案

您可以使用a Map<Character, IntUnaryOperator> :

Map<Character, IntUnaryOperator> commands = new HashMap<>();
commands.put('h', number -> funtion1(number) );
commands.put('t', number -> funtion1(number) );

// Invoke some command
char cmd = 'h';
IntUnaryOperator result= commands.get(cmd);

现在您可以传递int运算符的参数:

System.out.println(" Return value is " + result.applyAsInt(10));

关于java - 将参数传递给 HashMap 值中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46971251/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com