java_HashMap的遍历方法_4种

1.通过接收keySet来遍历:

        HashMap<String,String> map = new HashMap<>();
        map.put("bb","12");
        map.put("aa","13");
        for(String each:map.keySet()){
            System.out.println("key:"+each+"value:"+map.get(each));
        }    

 

输出为:

 

 2,通过entrySet来遍历

 

for(Map.Entry<String,String> each:map.entrySet()){
            System.out.println("key:"+each.getKey()+" value:"+each.getValue());
        }

 

输出为:

 

 3.使用迭代器遍历(实质上foreach语句就是迭代器实现)

Iterator test01 = map.entrySet().iterator();
        while(test01.hasNext()){
            System.out.println(test01.next());
        }

 

输出为:

 

 

4.通过valueSet来遍历(只能遍历到值,但是hashMap是加入有序的,所以不用担心和加入顺序不一样)

for(String each:map.values()){
            System.out.println(each);
        }

 

输出为:

 

 

 

希望对大家有所帮助

以上

posted @ 2020-02-08 21:54  醉生梦死_0423  阅读(543)  评论(0编辑  收藏  举报