Java 如何手动填写HashMap?
如何手动填写以下HashMapJava 如何手动填写HashMap?,java,hashmap,Java,Hashmap,如何手动填写以下HashMap public static final HashMap<String,int[]> AGE_GROUPS = {"18-24",{18,24}, "25-29",{25,29}, "30-39",{30,39},
public static final HashMap<String,int[]> AGE_GROUPS = {"18-24",{18,24},
"25-29",{25,29},
"30-39",{30,39},
"40-49",{40,49},
"50-59",{50,59},
"60-69",{60,69},
"70-79",{70,79},
"80+",{80,120}};
publicstaticfinalhashmap年龄组={18-24',{18,24},
"25-29",{25,29},
"30-39",{30,39},
"40-49",{40,49},
"50-59",{50,59},
"60-69",{60,69},
"70-79",{70,79},
"80+",{80,120}};
这称为静态初始化
private static final Map<Integer, String> myMap;
static {
Map<Integer, String> aMap = ....;
aMap.put(1, "one");
aMap.put(2, "two");
myMap = Collections.unmodifiableMap(aMap);
}
私有静态最终映射myMap;
静止的{
Map aMap=。。。。;
资产负债表(1,“一”);
aMap.put(2,“两”);
myMap=Collections.unmodifiableMap(aMap);
}
在你的情况下
public static final Map<String, int[]> AGE_GROUPS;
static{
Map<String, int[]> otherMap = new HashMap<String, int[]>();
otherMap.put( "10-20", new int[]{ 10, 11 } );
otherMap.put( "20-30", new int[]{ 20, 21 } );
AGE_GROUPS = Collections.unmodifiableMap( otherMap );
}
公共静态最终地图年龄组;
静止的{
Map otherMap=newhashmap();
otherMap.put(“10-20”,新int[]{10,11});
otherMap.put(“20-30”,新int[]{20,21});
年龄组=集合。不可修改地图(其他地图);
}
这是我使用助手方法的地方
public static Map<String, int[]> rangeMap(int... fromTo) {
Map<String,int[]> map = new LinkedHashMap<>();
for (int i = 0; i < fromTo.length; i += 2) {
String key = fromTo[i] + (fromTo[i+1] > 100 ? "+" : "-"+fromTo[i+1]);
map.put(key, new int[] { fromTo[i], fromTo[i+1]));
return Collections.unmodifiableMap(map);
}
public static final Map<String,int[]> AGE_GROUPS = rangeMap(
0, 17,
18, 24,
25, 29,
30, 39,
40, 49,
50, 59,
60, 69,
70, 79,
80, 120);
公共静态地图范围地图(int…fromTo){
Map Map=newlinkedhashmap();
对于(int i=0;i100?+“:”-“+fromTo[i+1]);
map.put(key,newint[]{fromTo[i],fromTo[i+1]);
返回集合。不可修改映射(map);
}
公共静态最终地图年龄组=范围地图(
0, 17,
18, 24,
25, 29,
30, 39,
40, 49,
50, 59,
60, 69,
70, 79,
80, 120);
绝对不是这样。没有地图(或列表)Java中的文本,因此您必须以老式的方式填充。Final不能在声明后设置,因此首先必须更改然后编辑它。请看一下使用guava ImmutableMap您可以使用双大括号初始化:注意性能问题:我的意思是不要使用这一行;`myMap=Collections.unmodifiableMap(aMap);`他可以使用自己的地图。不过还是编辑了我的答案,谢谢。你能给我的年龄组举个例子吗(HashMap?如何静态初始化?明白了!HashMap aMap=new HashMap();aMap.put(“18-24”,new int[]{18,24});不错,但不会生成“80+”
string作为最终映射。@Andreas修复了它。虽然如果你超过120岁,你不会超过80岁,但我同意,到目前为止,只有一个人这么老。我会选择999
或未定义,即int[1]
值作为“80+”
映射,但这是OP的选择。