Java分享笔记:使用entrySet方法获取Map集合中的元素

 1 /*---------------------------------
 2 使用entrySet方法取出Map集合中的元素:
 3 ....该方法是将Map集合中key与value的关系存入到了Set集合中,这个关系的数据类型是Map.Entry
 4 ....entrySet方法返回值类型的具体写法为:Set< Map.Entry<KeyType , ValueType> >
 5 ----------------------------------*/
 6 package pack04;
 7 
 8 import java.util.*;
 9 
10 public class MapDemo {
11     public static void main(String[] args) {
12 
13         Map<Integer, String> ma = new HashMap<Integer, String>();
14 
15         //给集合中存入元素
16         ma.put(1, "abc01");    //这里将基本数据类型自动装箱
17         ma.put(2, "abc02");
18         ma.put(3, "abc03");
19         ma.put(4, "abc04");
20         
21         //将Map集合当中的映射关系取出,存入到Set集合当中
22         Set< Map.Entry<Integer, String> > entryset = ma.entrySet();
23         
24         //取迭代器
25         Iterator< Map.Entry<Integer, String> > it = entryset.iterator();
26         
27         //获取Map集合中的元素
28         while( it.hasNext() ) {
29             Map.Entry<Integer, String> en = it.next();
30             Integer maKey = en.getKey();
31             String maValue = en.getValue();
32             
33             System.out.println( maKey + " : " + maValue );
34         }
35         
36     }
37 }

注:希望与各位读者相互交流,共同学习进步。

原文地址:https://www.cnblogs.com/EarthPioneer/p/9351996.html