1. 使用EntrySet迭代器遍历HashMap:
HashMap<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);

Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
    Map.Entry<String, Integer> entry = iterator.next();
    String key = entry.getKey();
    Integer value = entry.getValue();
    System.out.println(key + " = " + value);
}
  1. 使用KeySet迭代器遍历HashMap:
HashMap<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);

Iterator<String> iterator = map.keySet().iterator();
while (iterator.hasNext()) {
    String key = iterator.next();
    Integer value = map.get(key);
    System.out.println(key + " = " + value);
}
  1. 使用Java 8的forEach方法遍历HashMap:
HashMap<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);

map.forEach((key, value) -> System.out.println(key + " = " + value));
Java HashMap 迭代方法:三种遍历技巧详解

原文地址: https://www.cveoy.top/t/topic/p4ZV 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录