posts - 397,comments - 0,views - 25332

Map集合遍历的第二种方式:使用Entry对象遍历

Map集合中的方法:

Set<Map.Entry<K,v>> entrySet()返回此映射中包含的映射关系的Set 视图。

使用Map集合中的方法entrySet(),把Nap集合中多个Entry对象取出来,存储到一个set集合中

.遍历set集合,获取每一个Entry对象/使用迭代器遍历set集合

 

使用Entry对象中的方法getKey()和getvalue()获取键与值

 

 

 增强for

 

 

 

 

HashMap存储自定义类型键值

HashMap存储自定义类型键值

Map集合保证key是唯一的:作为key的元素,必须重写hashcode方法和equals方法,以保证key唯一

 

 

使用keyset

复制代码
HashMap<String, Person> map = new HashMap<>();
        map.put("北京",new Person("张三",18));
        map.put("上海",new Person("李四",19));
        map.put("广州",new Person("王五",20));
        map.put("北京",new Person("赵六",18));

        Set<String> set = map.keySet();
        for (String key:set){
            Person person = map.get(key);
            System.out.println(key+person);
        }
复制代码

使用entrySet和增强for遍历Map集合

注意实体类重写hashcode方法

复制代码
HashMap<Person, String> map = new HashMap<>();
        map.put(new Person("女王",18),"英国");
        map.put(new Person("秦始皇",18),"秦国");
        map.put(new Person("普京",18),"俄罗斯");
        map.put(new Person("女王",18),"巴基斯坦");
        Set<Map.Entry<Person, String>> set = map.entrySet();
        for (Map.Entry<Person,String> entry : set){
            Person key = entry.getKey();
            String value = entry.getValue();
            System.out.println(key+value);
        }
复制代码

 

 

posted on   淤泥不染  阅读(34)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示