标签:bsp 键值对 str test keyset set 通过 class system
HashMap 集合的遍历:
两种方式遍历HashMap:
1 //集合hashMap的遍历:
2 //方式一:
3 @Test
4 public void testMethod1(){
5 HashMap<String, String> map = new HashMap<String,String>();
6 map.put("张三","23");
7 map.put("李四","28");
8 map.put("王二","32");
9 map.put("麻子","28");
10 //获取所有键的集合(map.keySet()方法)。获取所有值的方法:(map.values());
11 Set<String> keySet = map.keySet();
12 //遍历键的集合:
13 for(String key:keySet){
14 //通过key,获取value:
15 String value = map.get(key);
16 System.out.println(key+"="+value);
17 }
18 }
19 //方式二:
20 @Test
21 public void testMethod2(){
22 HashMap<String, String> map = new HashMap<String,String>();
23 map.put("张三","23");
24 map.put("李四","28");
25 map.put("王二","32");
26 map.put("麻子","28");
27 //获取键值对对象:
28 Set<Map.Entry<String, String>> entries = map.entrySet();
29 //遍历键值对对象:
30 for(Map.Entry<String, String> me :entries){
31 //从键值对对象中分别取值key、value:
32 String key = me.getKey();
33 String value = me.getValue();
34 System.out.println(key+"="+value);
35 }
36 }
标签:bsp 键值对 str test keyset set 通过 class system
原文地址:https://www.cnblogs.com/dw3306/p/9430487.html