HashMap的遍历

时间:2021-05-21 23:59:45   收藏:0   阅读:44

HashMap的遍历:

1.使用map.keyset()与map.values()遍历键值

HashMap<String,Integer> hashMap=new HashMap<>();
        hashMap.put("hello",1);
        hashMap.put("hi",2);
        for(String a:hashMap.keySet())
        {
            System.out.println(a);//键
        }
        for(Integer integer:hashMap.values())
        {
            System.out.println(integer);//值
        }

2.使用entryset()

HashMap<String,Integer> hashMap=new HashMap<>();
        hashMap.put("hello",1);
        hashMap.put("hi",2);
        for(Map.Entry<String,Integer> a: hashMap.entrySet())
        {
            System.out.println(a.getKey());
            System.out.println(a.getValue());
        }

3.使用Iterator迭代

HashMap<String,Integer> hashMap=new HashMap<>();
        hashMap.put("hello",1);
        hashMap.put("hi",2);
        Iterator<Map.Entry<String,Integer>> iterator=hashMap.entrySet().iterator();
        while(iterator.hasNext())
        {
            Map.Entry<String,Integer> a=iterator.next();
            System.out.println(a.getKey()+a.getValue());
        }

 

原文:https://www.cnblogs.com/mlqq/p/14797628.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!