1. 程式人生 > >遍歷Map集合的三種方法

遍歷Map集合的三種方法

Map<String,Integer> map=new HashMap<String,Integer>();
        map.put("aa",11);
        map.put("bb",22);
        map.put("cc",33);

        //遍歷Map集合方法1: 取出KEYS
        Set<String> set=map.keySet();
        Iterator it=set.iterator();
        while(it.hasNext()){
            String key=(String) it.next();

            System.out.println("--->"+map.get(key));
        }
        System.out.println("=============");
        //遍歷Map集合方法2:GET VALUES
        Collection<Integer>  col =map.values();
        for(Iterator itt=col.iterator();itt.hasNext();){
            System.out.println("---->"+itt.next());

        }
        //遍歷Map集合方法3:把KEY VALUE都取出,再分開
        Set<Entry<String,Integer>> st=map.entrySet();
        Iterator ite=st.iterator();
        while(ite.hasNext()){
            Entry<String,Integer> entry=(Entry<String, Integer>) ite.next();
            System.out.println("key--->"+entry.getKey()+"----value--->"+entry.getValue());

        }