软件编程
位置:首页>> 软件编程>> java编程>> Java使用entrySet方法获取Map集合中的元素

Java使用entrySet方法获取Map集合中的元素

作者:Killer-V  发布时间:2022-08-06 17:41:05 

标签:java,entrySet,元素

本文为大家分享了使用entrySet方法获取Map集合中元素的具体代码,供大家参考,具体内容如下


/*---------------------------------
使用entrySet方法取出Map集合中的元素:
....该方法是将Map集合中key与value的关系存入到了Set集合中,这个关系的数据类型是Map.Entry
....entrySet方法返回值类型的具体写法为:Set< Map.Entry<KeyType , ValueType> >
----------------------------------*/
package pack04;

import java.util.*;

public class MapDemo {
 public static void main(String[] args) {

Map<Integer, String> ma = new HashMap<Integer, String>();

//给集合中存入元素
   ma.put(1, "abc01");  //这里将基本数据类型自动装箱
   ma.put(2, "abc02");
   ma.put(3, "abc03");
   ma.put(4, "abc04");

//将Map集合当中的映射关系取出,存入到Set集合当中
   Set< Map.Entry<Integer, String> > entryset = ma.entrySet();

//取迭代器
   Iterator< Map.Entry<Integer, String> > it = entryset.iterator();

//获取Map集合中的元素
   while( it.hasNext() ) {
     Map.Entry<Integer, String> en = it.next();
     Integer maKey = en.getKey();
     String maValue = en.getValue();

System.out.println( maKey + " : " + maValue );
   }

}
}

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

来源:https://www.cnblogs.com/EarthPioneer/p/9351996.html

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com