【Java】java 遍历map对象的四种方式

1. 使用Map.Entry遍历

Map<String, ArrayList<String>> map = new HashMap<>();

for (Map.Entry<String, ArrayList<String>> entry : map.entrySet()) {
     String key = entry.getKey();
     ArrayList<String> item = entry.getValue();
 
     // ....
}

2. for-each 循环遍历keys和values

for (String s : map.keySet()) {
    // ...
}

for (ArrayList<String> e : map.values()) {
    // ...
}

3. 使用Iterator

Map<Integer, Integer> map = new HashMap<>();  
  
Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator();  
  
while (entries.hasNext()) {  
   Map.Entry<Integer, Integer> entry = entries.next();  
   // ...
}  

4. 二次取值

Map<Integer, Integer> map = new HashMap<>();  
  
for (Integer key : map.keySet()) {    
    Integer value = map.get(key);    
    // ...
}  
    原文作者:dmcler
    原文地址: https://blog.csdn.net/kturing/article/details/73302029
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞