[Java] java中遍历HashMap的方法 →→→→→进入此内容的聊天室

来自 , 2021-04-03, 写在 Java, 查看 134 次.
URL http://www.code666.cn/view/84fec9a8
  1. import java.util.*;  
  2. public class MapTest {  
  3.     static HashMap<String, Integer> hashMap = new HashMap<String, Integer>();    
  4.     public static void main(String [] args) {  
  5.         hashMap.put("one", 1);  
  6.         hashMap.put("two", 2);  
  7.         hashMap.put("three", 3);  
  8.         hashMap.put("four", 4);  
  9.         hashMap.put("five", 5);    
  10.         Iterator iter = hashMap.entrySet().iterator();    
  11.         // the first method to travel the map
  12.         while (iter.hasNext()) {  
  13.             Map.Entry<String, Integer> entry = (Map.Entry<String, Integer>) iter.next();  
  14.             String key = entry.getKey();  
  15.             Integer value = entry.getValue();    
  16.             System.out.println(key + " " + value);  
  17.         }    
  18.         iter = hashMap.keySet().iterator();  
  19.         // the second method to travel the map  
  20.         while (iter.hasNext()) {  
  21.             String key = (String) iter.next();  
  22.             Integer value = hashMap.get(key);      
  23.             System.out.println(key + " " + value);  
  24.         }  
  25.     } // close main()  
  26. }  
  27. //java/6067

回复 " java中遍历HashMap的方法"

这儿你可以回复上面这条便签

captcha