2017-10-27 3 views
2

ハッシュマップの値で関数にパラメータを渡す私は次のように私はハッシュマップの値の関数存在を呼び出していたシナリオを持っています

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

私の質問は、それは私が関数にパラメータを渡すことができている(FUNCTION 1 )ハッシュマップ値を取得するとき、つまりcommands.get(cmd)を使用するとき。

ありがとうございます。

+0

'function1'は(その署名が何であるか)のように何を求めていますか?それは 'int function1(int i){...}'ですか? – assylias

+0

整数をパラメータとする単純な関数です。 like-static int funtion1(int num) – user7749322

+3

確かに、この場合、['IntFunction'](https://docs.oracle.com/javase/9​​/docs/api/java)を使用する必要があります。 /util/function/IntSupplier.html)ではなく、 '' IntSupplier''(https://docs.oracle.com/javase/9​​/docs/api/java/util/function/IntSupplier.html)の代わりに使用できます。 – Turing85

答えて

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)); 
+0

ありがとう@assylias。番号をどうするか教えてください。 "ラムダ式のパラメータ番号は、囲みスコープで定義された別のローカル変数を再宣言できません"というエラーが表示されます。 – user7749322

+0

@ user7749322すでに 'number'変数がどこかで宣言されているためです。私の例で 'number'を' i'に変更するか、コードから数値変数を削除してください。 – assylias

+0

ありがとう@assylias。 – user7749322

関連する問題