HashMap 的遍历

一. 使用entries遍历

Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}

二. 遍历keys或values

Map<Integer, Integer> map = new HashMap<Integer, Integer>();
//遍历map中的键
for (Integer key : map.keySet()) {
    System.out.println("Key = " + key);
}
//遍历map中的值
for (Integer value : map.values()) {
    System.out.println("Value = " + value);
}

三. 使用Iterator遍历

// 使用泛型:
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
    Map.Entry<Integer, Integer> entry = entries.next();
    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
// 不使用泛型:
Map map = new HashMap();
Iterator entries = map.entrySet().iterator();
while (entries.hasNext()) {
    Map.Entry entry = (Map.Entry) entries.next();
    Integer key = (Integer)entry.getKey();
    Integer value = (Integer)entry.getValue();
    System.out.println("Key = " + key + ", Value = " + value);
}

四. 通过键找值遍历(效率低)

Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Integer key : map.keySet()) {
    Integer value = map.get(key);
    System.out.println("Key = " + key + ", Value = " + value);
}

五. Map的判断删除内部参数

public static void main(String[] args) {
    Map<Integer, Boolean> map = new HashMap<>();
    map.put(1, true);
    map.put(2, false);
    map.put(3, true);
    map.put(4, false);
    map.put(5, true);
    map.put(6, false);
    map.put(7, true);
    map.put(8, false);

    map.entrySet().removeIf(next -> !next.getValue());

    System.out.println(map);
}

参考地址:

https://blog.csdn.net/tjcyjd/article/details/11111401