HashMap的遍历以及更改方式

2022-02-27  本文已影响0人  nobigogle

HashMap一共有四种遍历方式。

Key和Value

    public static void printHashMap1(HashMap<Integer, Integer> hashMap) {
        Iterator<Map.Entry<Integer, Integer>> iterator = hashMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<Integer, Integer> entry = iterator.next();
            System.out.print(entry.getKey());
            System.out.println(entry.getValue());
        }
    }
    public static void printHashMap2(HashMap<Integer, Integer> hashMap) {
        for (Map.Entry<Integer, Integer> entry : hashMap.entrySet()){
            System.out.print(entry.getKey());
            System.out.println(entry.getValue());
        }
    }
    public static void printHashMap3(HashMap<Integer, Integer> hashMap) {
        for (Integer key : hashMap.keySet()){
            System.out.print(key);
            System.out.println(hashMap.get(key));
        }
    }

Value

    public static void printHashMap4(HashMap<Integer, Integer> hashMap) {
        for (Integer value : hashMap.values()){
            System.out.print(value);
        }
    }

更新HashMap,删除某个Key

    public static void removeHashMap(HashMap<Integer, Integer> hashMap) {
        Iterator<Map.Entry<Integer, Integer>> iterator = hashMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<Integer, Integer> entry = iterator.next();
            iterator.remove();
            System.out.print(entry.getKey());
            System.out.println(entry.getValue());
        }
    }
上一篇 下一篇

猜你喜欢

热点阅读