2

I am having a scenario where I am calling a function present in hashmap value as follows,

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

My question is that can I pass the parameter to the function (function1) when getting the hashmap value i.e. when using commands.get(cmd).

Thank you.

3
  • What does function1 look like (what is its signature)? Is it an int function1(int i) { ... }? Commented Oct 27, 2017 at 9:03
  • It is a simple function which takes an integer as a parameter. like- static int funtion1(int num) Commented Oct 27, 2017 at 9:04
  • 3
    You can surely, but in this case you would have to use an IntFunction instead of an IntSupplier. Commented Oct 27, 2017 at 9:10

1 Answer 1

5

You can use 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);

Now you can pass an int parameter to the operator:

System.out.println(" Return value is " + result.applyAsInt(10));
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you @assylias. Can you please tell what to do with the number. It is giving me error as" Lambda expression's parameter number cannot redeclare another local variable defined in an enclosing scope. "
@user7749322 because you already have a number variable declared somewhere. Just change number to i in my example or remove the number variable from your code.
How can I alter the program to return an string? Or what to do for getting a different return value.
To return a String, you would need a IntFunction<String> and function1 would need to look like String function1(int i) { return "a string"; }.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.