标签:style 取值 日常 [] color sys put str main
日常编码过程大部分遇到List遍历,数组遍历等等,但是一遇到Map遍历总会停下想想、网上查查,以此总结以下四种遍历方式:
1 public static void main(String[] args) { 2 Map<String, String> testMap = new HashMap(); 3 testMap.put("key1", "value1"); 4 testMap.put("key2", "value2"); 5 testMap.put("key3", "value3"); 6 7 //第一种:二次取值,使用较多的一种 8 for (String key : testMap.keySet()) { 9 System.out.println("key:" + key + ",value:" + testMap.get(key)); 10 } 11 //第二种:利用interator遍历 12 Iterator iterator = testMap.entrySet().iterator(); 13 while (iterator.hasNext()) { 14 Map.Entry<String, String> entry = (Map.Entry<String, String>) iterator.next(); 15 System.out.println("key:" + entry.getKey() + ",value:" + entry.getValue()); 16 } 17 //第三种:通过entrySet遍历 推荐,尤其容量大 18 for (Map.Entry<String, String> entry : testMap.entrySet()) { 19 System.out.println("key:" + entry.getKey() + ",value:" + entry.getValue()); 20 } 21 //第四种:只遍历value,不可遍历key 22 for (String value : testMap.values()) { 23 System.out.println("value:" + value); 24 } 25 }
标签:style 取值 日常 [] color sys put str main
原文地址:https://www.cnblogs.com/cpy0818/p/9916926.html