HashMap常见问题分析

一、HashMap中Value可以相同,但是键不可以相同
当插入HashMap的key相同时,会覆盖原有的Value,且返回原Value值,看下面的程序:
[Java] 纯文本查看 复制代码
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
public class Test {
  
    public static void main(String[] args) {
         
        HashMap<String,Integer> map = new HashMap<String,Integer>();
  
        //出入两个Value相同的值,没有问题
        map.put("egg", 1);
        map.put("niu", 1);
         
        //插入key相同的值,看返回结果
        int egg = (Integer) map.put("egg", 3);
         
        System.out.println(egg);   //输出1
        System.out.println(map.get("egg"));   //输出3,将原值1覆盖
        System.out.println(map.get("niu"));   //输出1
    }
}

相同的键会被覆盖,且返回原值。

二、HashMap按值排序
给定一个数组,求出每个数据出现的次数并按照次数的由大到小排列出来。我们选用HashMap来做,key存储数组元素,值存储出现的次数,最后用Collections的sort方法对HashMap的值进行排序。代码如下:
[Java] 纯文本查看 复制代码
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class Test {
  
    public static void main(String[] args) {
  
        int data[] = { 2, 5, 2, 3, 5, 2, 3, 5, 2, 3, 5, 2, 3, 5, 2,
                7, 8, 8, 7, 8, 7, 9, 0 };
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for (int i : data) {
            if (map.containsKey(i)) {//判断HashMap里是否存在
                map.put(i, map.get(i) + 1);//已存在,值+1
            } else {
                map.put(i, 1);//不存在,新增
            }
        }
        //map按值排序
        List<Map.Entry<Integer, Integer>> list = new ArrayList<Map.Entry<Integer, Integer>>(
                map.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<Integer, Integer>>() {
            public int compare(Map.Entry<Integer, Integer> o1,
                    Map.Entry<Integer, Integer> o2) {
                return (o2.getValue() - o1.getValue());
            }
        });
        for (Map.Entry<Integer, Integer> m : list) {
            System.out.println(m.getKey() + "-" + m.getValue());
        }
    }
  
}
 
输出:

2-6
5-5
3-4
8-3
7-3
9-1
0-1

评论

暂无评论