HashMap的遍历

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());
        }

 4.做题时遇见的

hashMap.getOrDefault(words,0) //如果存在就返回对应的value 不存在就返回0

 

posted @ 2021-05-21 22:32  莫恼卿卿  阅读(74)  评论(0编辑  收藏  举报