将参数传递给hashmap值中的函数

时间:2017-10-27 09:00:53

标签: java java-8

我有一个场景,我在调用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值时将参数传递给函数(function1),即使用commands.get(cmd)时。

谢谢。

1 个答案:

答案 0 :(得分:5)

您可以使用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));