码迷,mamicode.com
首页 > 其他好文 > 详细

获取map集合中的键和值

时间:2016-10-29 19:15:15      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:ati   添加   span   div   val   键值   void   out   color   

1、根据键找值

public static void main(String[] args) {
        //创建集合对象
        Map<String ,Integer> map=new HashMap<String ,Integer>();
        //创建元素并添加到集合
        map.put("hello", 1);
        map.put("world", 2);
                Set <String> set=map.keySet();
        for(String key:set){
            Integer value=map.get(key);
            System.out.println(key+"___"+value);
        }
 }

2、根据键值对对象找键和值方法1:

    键值对对象可以比喻成结婚证,而键和值就像是结婚证上的2个人名。

public static void main(String[] args) {
        //创建集合对象
        Map<String ,Integer> map=new HashMap<String ,Integer>();
        //创建元素并添加到集合
        map.put("hello", 1);
        map.put("world", 2);
        //1、获取所有键值对对象的集合
        Set<Map.Entry<String , Integer>> set=map.entrySet();
        //2、获取Iterator对象,并用此对象的方法遍历键值对对象
        Iterator <Map.Entry<String, Integer>> iter=set.iterator();
        while(iter.hasNext()){
            Map.Entry<String, Integer> me=iter.next();
        //3、根据键值对对象获取键和值
            System.out.println(me.getKey()+me.getValue());
        }
}

3、根据键值对对象找键和值方法2:

public static void main(String[] args) {
  //创建集合对象
  Map<String ,Integer> map=new HashMap<String ,Integer>();
  //创建元素并添加到集合
  map.put("hello", 1);
  map.put("world", 2);
   //1、获取所有键值对对象的集合
  Set <Map.Entry<String, Integer>> set=map.entrySet();
  //2、foreach遍历键值对对象的集合,得到每一个键值对对象
  for(Map.Entry<String, Integer> me:set){
   //3、根据键值对对象获得键和值
   System.out.println(me.getKey()+"————"+me.getValue());
  }
}

 

获取map集合中的键和值

标签:ati   添加   span   div   val   键值   void   out   color   

原文地址:http://www.cnblogs.com/flyang/p/6011393.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!