java 遍历map对象的四种方式

1. 使用Map.Entry遍历


Map> map = new HashMap<>();

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


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


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

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


3. 使用Iterator


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


4. 二次取值


Map map = new HashMap<>();  
  
for (Integer key : map.keySet()) {    
    Integer value = map.get(key);    
    // ...
}  



你可能感兴趣的:(java)