如何手动填写HashMap?

时间:2015-09-04 06:25:50

标签: java hashmap

如何手动填写以下HashMap?

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}};

2 个答案:

答案 0 :(得分:9)

这称为静态初始化。

 private static final Map<Integer, String> myMap;
    static {
        Map<Integer, String> aMap = ....;
        aMap.put(1, "one");
        aMap.put(2, "two");
        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 );

    }

答案 1 :(得分:0)

这是我使用辅助方法的地方

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