Map集合的四种遍历
map集合的遍历有四种,一是对键的遍历,二是对值的遍历,三是利用键查找对应的值,四是通过Map.entrySet遍历key和value。
1 @Test 2 public void demo() { 3 Map<String, String> map=new HashMap<String, String>(); 4 map.put("aa", "王琦"); 5 map.put("bb", "张三"); 6 map.put("cc", "李四"); 7 map.put("dd", "王五"); 8 9 Set<String> set = map.keySet(); 10 for (String string : set) { 11 System.out.println(string); 12 } 13 14 System.out.println("----------------------------------"); 15 16 Collection<String> values = map.values(); 17 for (String string : values) { 18 System.out.println(string); 19 } 20 21 System.out.println("----------------------------------"); 22 23 Set<String> set2 = map.keySet(); 24 for (String string : set2) { 25 System.out.println(string+"-----"+map.get(string)); 26 } 27 28 System.out.println("=============================="); 29 30 Set<Entry<String, String>> entrySet = map.entrySet(); 31 for (Entry<String, String> entry : entrySet) { 32 System.out.println(entry); 33 } 34 35 }
运行结果