-- 创造无限可能

java开发技巧:循环输出map

2023-06-04 09:44:55
507 人浏览 0 人点赞
有用,点赞支持一下

场景

现在有一个map对象,需要遍历所有元素进行操作

方案

  1. for
Map<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);

for (Map.Entry<String, Integer> entry : map.entrySet()) {
    String key = entry.getKey();
    Integer value = entry.getValue();
    System.out.println(key + ": " + value);
}
  1. forEach
Map<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));