Java HashMap 遍历、删除、排序

首先创建一个map对象,并依次放入几个测试数据

        HashMap<String, Integer> map = new HashMap<String, Integer>();
        map.put("One", 1);
        map.put("Two", 2);
        map.put("Three", 3);

1.遍历

①方法一

        for (HashMap.Entry<String, Integer> entry : map.entrySet()) {
            String key = entry.getKey();
            Integer val = entry.getValue();
        }

②方法二

        for (Iterator<HashMap.Entry<String, Integer>> it = map.entrySet().iterator(); it.hasNext();) {
            HashMap.Entry<String, Integer> entry = it.next();
            String key = entry.getKey();
            Integer val = entry.getValue();
        }

2.删除

        for (Iterator<HashMap.Entry<String, Integer>> it = map.entrySet().iterator(); it.hasNext(); ) {
            HashMap.Entry<String, Integer> entry = it.next();
            //删除key值为Two的数据
            if (entry.getKey().equals("Two")) {
                it.remove();
            }
        }

3.排序

        //创建一个用于对yourMap进行排序的list
        List<HashMap.Entry<String, Integer>> list = new ArrayList(yourMap.entrySet());

        //提供一个匿名的比较函数对象(从大到小进行输出)
        Collections.sort(list, new Comparator<HashMap.Entry<String, Integer>>() {
            public int compare(HashMap.Entry<String, Integer> o1, HashMap.Entry<String, Integer> o2) {
                return o2.getValue() - o1.getValue(); //这里是从大到小进行排序,如果需从小到大进行排序则将o1和o2互换即可
            }
        });

        //按排序输出list中的内容
        for (HashMap.Entry<String, Integer> entry : list) {
            String key = entry.getKey();
            Integer val = entry.getValue();
        }

以上。

原文地址:https://www.cnblogs.com/chevin/p/9260598.html