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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

Killer-V   2021-03-30 我要评论

本文为大家分享了使用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 );
    }
    
  }
}

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

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们