2014/07/10

[Java] HashMap簡易使用方法及如何排序


宣告:前面KeyType, 後面ValueType

?
1
2
HashMap<String, Integer> hashMap = new HashMap<String, Integer>();

放入新元素

?
1
hashMap.put(Key,Value);

得到特定Key的Value:若無此Key回傳null

?
1
hashMap.get(Key);

更新特定Key,Value:以加一為例

?
1
hashMap.put(Key, hashMap.get(Key)+1);

輸出

?
1
2
3
for(KetType Key: hashMap.keySet()){
    System.out.println(Key, hashMap.get(Key));
}

排序後輸出(以降冪為例):利用ArrayList

?
1
2
3
4
5
6
7
8
9
10
11
    List<map.entry<String, Integer>> list = new ArrayList<map.entry<string,integer>>(hashMap.entrySet());
        Collections.sort(list,new Comparator<map.entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> entry1, Map.Entry<String, Integer> entry2) {
                return (entry2.getValue()-entry1.getValue());
            }
        });
        for (Map.Entry<String, Integer> entry:list){
            System.out.println(entry.getKey()+" : "+hashMap.get(entry.getKey()));
        }