在 Java 中循环 Map 有以下几种方法:

  1. 使用 Map.keySet() 方法获取键集合,然后通过循环遍历键集合获取对应的值:
Map<String, Integer> map = new HashMap<>();
// 添加键值对
for (String key : map.keySet()) {
    Integer value = map.get(key);
    // 处理键值对
}
  1. 使用 Map.entrySet() 方法获取键值对集合,然后通过循环遍历键值对集合获取键和值:
Map<String, Integer> map = new HashMap<>();
// 添加键值对
for (Map.Entry<String, Integer> entry : map.entrySet()) {
    String key = entry.getKey();
    Integer value = entry.getValue();
    // 处理键值对
}
  1. 使用 Java 8 中的 Lambda 表达式:
Map<String, Integer> map = new HashMap<>();
// 添加键值对
map.forEach((key, value) -> {
    // 处理键值对
});
``
java循环map

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

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