方式一:entrySet()
遍历HashMap的entrySet键值对集合
1.通过HashMap.entrySet()得到键值对集合;
2.通过迭代器Iterator遍历键值对集合得到key值和value值;
1 @Test
2 public void testHashMap01(){
3 // 创建一个key和value均为String的Map集合
4 Map<String, String> map = new HashMap<String, String>();
5 map.put("1", "11");
6 map.put("2", "22");
7 map.put("3", "33");
8 // 获取键值对的迭代器
9 Iterator it = map.entrySet().iterator();
10 while (it.hasNext()) {
11 Map.Entry entry = (Map.Entry) it.next();
12 String key = (String) entry.getKey();
13 String value = (String) entry.getValue();
14 System.out.println("key:" + key + "---" + "value:" + value);
15 }
16 }
17 输出结果:
18 key:1---value:11
19 key:2---value:22
20 key:3---value:33
方式二:keySet()
遍历HashMap键的Set集合获取值;
1.通过HashMap.keySet()获得键的Set集合;
2.遍历键的Set集合获取值;
1 @Test
2 public void testHashMap02(){
3 // 创建一个key和value均为String的Map集合
4 Map<String, String> map = new HashMap<String, String>();
5 map.put("1", "11");
6 map.put("2", "22");
7 map.put("3", "33");
8 // 获取键集合的迭代器
9 Iterator it = map.keySet().iterator();
10 while (it.hasNext()) {
11 String key = (String) it.next();
12 String value = (String) map.get(key);
13 System.out.println("key:" + key + "---" + "value:" + value);
14 }
15 }
16 输出结果:
17 key:1---value:11
18 key:2---value:22
19 key:3---value:33
方式三:values()
遍历HashMap“值”的集合;
1.通过HashMap.values()得到“值”的集合
2.遍历“值”的集合;
1 @Test
2 public void testHashMap03(){
3 // 创建一个key和value均为String的Map集合
4 Map<String, String> map = new HashMap<String, String>();
5 map.put("1", "11");
6 map.put("2", "22");
7 map.put("3", "33");
8 // 获取值集合的迭代器
9 Iterator it = map.values().iterator();
10 while (it.hasNext()) {
11 String value = (String) it.next();
12 System.out.println("value:" + value);
13 }
14 }
15 输出结果:
16 value:11
17 value:22
18 value:33