「Java」HashMapに指定キーから値を返すサンプル
書式
Map<String, Integer> mp = new HashMap<String, Integer>();
mp.get(キー)
使用例
package com.arkgame.study;
import java.util.HashMap;
import java.util.Map;
public class SampleC {
public static void main(String[] args) {
int x = 5, res;
//getLen関数を呼び出す
res = getLen("C03") + x;
System.out.println("結果: " + res);
}
//getLenメソッドの定義
public static int getLen(String str) {
Map<String, Integer> mp = new HashMap<String, Integer>();
mp.put("k01", 11);
mp.put("B02", 22);
mp.put("C03", 32);
mp.put("D04", 45);
//指定されたキーがマップされている値を返します。その
return mp.get(str);
}
}
package com.arkgame.study;
import java.util.HashMap;
import java.util.Map;
public class SampleC {
public static void main(String[] args) {
int x = 5, res;
//getLen関数を呼び出す
res = getLen("C03") + x;
System.out.println("結果: " + res);
}
//getLenメソッドの定義
public static int getLen(String str) {
Map<String, Integer> mp = new HashMap<String, Integer>();
mp.put("k01", 11);
mp.put("B02", 22);
mp.put("C03", 32);
mp.put("D04", 45);
//指定されたキーがマップされている値を返します。その
return mp.get(str);
}
}
package com.arkgame.study; import java.util.HashMap; import java.util.Map; public class SampleC { public static void main(String[] args) { int x = 5, res; //getLen関数を呼び出す res = getLen("C03") + x; System.out.println("結果: " + res); } //getLenメソッドの定義 public static int getLen(String str) { Map<String, Integer> mp = new HashMap<String, Integer>(); mp.put("k01", 11); mp.put("B02", 22); mp.put("C03", 32); mp.put("D04", 45); //指定されたキーがマップされている値を返します。その return mp.get(str); } }
実行結果
結果: 37