我有一个场景,我在调用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());
Run Code Online (Sandbox Code Playgroud)
我的问题是,我可以在获取hashmap值时将参数传递给函数(function1),即使用commands.get(cmd)时.
谢谢.
你可以使用一个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);
Run Code Online (Sandbox Code Playgroud)
现在您可以将int参数传递给运算符:
System.out.println(" Return value is " + result.applyAsInt(10));
Run Code Online (Sandbox Code Playgroud)