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);    
    // ...
}  



上一篇:linux设置LD_LIBRARY_PATH变量


下一篇:andriod之路,开发环境配置