A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© Justfeeling 中级黑马   /  2014-8-10 22:51  /  1439 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

public class MapTest {
        public static void main(String[] args) {
                method();
        }
        public static void method(){
                Map<String ,Integer> map=new HashMap<String,Integer>();
                map.put("a", 1);
                map.put("b", 2);
                map.put("c", 3);
                map.put("d", 4);
                map.put("e", 5);
//     第一种方法:
//                1.调用Map接口中keySet()方法,将Map集合中的键存储到Set集合中。
//                2.迭代Set集合,获取出所有的键。
//                3.it.next()方法,返回的是String类,Map集合中的键。
//                4.通过Map集合的get()方法,传递键,获取值。

Set<String> set=map.keySet();
                Iterator<String> it=set.iterator();
                while(it.hasNext()){
                        String key=it.next();
                        Integer value = map.get(key);  
                        System.out.println(key+"  "+value);
                }

//     第二种方法:
//                调用Map接口中entrySet()方法,获取键值对映射关系对象Entry,对                象存储到Set集合。
//                迭代器,迭代Set集合。
//                it.next()获取出来的是键值对映射关系对象Map.Entry。
//                利用键值对   映射关系对象中的方法,获取getKey()、getValue()。               
                Set<Entry<String,Integer>> set=map.entrySet();
                Iterator<Entry<String,Integer>> it=set.iterator();
                while(it.hasNext()){
                        Map.Entry<String, Integer> me=it.next();
                        String key=me.getKey();
                        Integer value=me.getValue();
                        System.out.println(key+"  "+value);
                }
        }
}

1 个回复

倒序浏览
学习了,不过貌似还有第三种,就是逐个去key,然后循环。
回复 使用道具 举报 1 0
您需要登录后才可以回帖 登录 | 加入黑马