1 Map接口概述

l  Map中的集合,元素是成对存在的(理解为夫妻)。每个元素由键与值两部分组成,通过键可以找对所对应的值。

l  Collection中的集合称为单列集合,Map中的集合称为双列集合。

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

l  需要注意的是,Map中的集合不能包含重复的键,值可以重复;每个键只能对应一个值。

Map中常用的集合为HashMap集合、LinkedHashMap集合。

 

Map集合的遍历:

1.keySet

Map集合的用法 随笔 第1张
public class Demo01 { public static void main(String[] args) { Map<Integer,String> map=new HashMap<Integer,String>(); //向map中添加键值对 map.put(1, "熊大"); map.put(2, "光头强"); map.put(3, "熊二"); map.put(2, "光头强"); //根据key获取value System.out.println(map.get(3)); //删除 map.remove(1); //遍历方式1:keySet方法 Set<Integer>set=map.keySet(); for(Integer key:set){ System.out.println(map.get(key)); } Iterator<Integer>it=set.iterator(); while(it.hasNext()){ System.out.println(map.get(it.next())); } }
Map集合的用法 随笔 第2张

2.entrySet

Map集合的用法 随笔 第3张
public class Demo02 { public static void main(String[] args) { Map<Integer,String> map=new HashMap<Integer,String>(); //向map中添加键值对 map.put(1, "熊大"); map.put(2, "光头强"); map.put(3, "熊二"); map.put(2, "光头强"); //遍历方式2:Entry Set<Map.Entry<Integer, String>>set=map.entrySet(); for(Map.Entry<Integer, String>entry:set){ System.out.println(entry.getKey()+"\t"+entry.getValue()); } } }
Map集合的用法 随笔 第4张

练习:

Iractor,for和entrySet,keySet遍历Map集合

 

Map集合的用法 随笔 第5张
public class Demo04 { public static void main(String[] args) { Map<GirlFriend,String>map=new HashMap<GirlFriend,String>(); //创建对象 GirlFriend g1=new GirlFriend("吴宣仪",24,166); GirlFriend g2=new GirlFriend("杨超越",21,168); GirlFriend g3=new GirlFriend("朴孝敏",28,167); GirlFriend g4=new GirlFriend("罗玉凤",34,165); //向map集合中添加key和value map.put(g1, "张三"); map.put(g2, "李四"); map.put(g3, "王五"); map.put(g4, "李四"); //遍历entrySet+for Set<Map.Entry<GirlFriend,String>>set=map.entrySet(); for(Map.Entry<GirlFriend, String> entry:set){ System.out.println(entry.getKey()+"\t"+entry.getValue()); } System.out.println("==============================="); //entry+iterator Iterator<Map.Entry<GirlFriend, String>>it=set.iterator(); while(it.hasNext()){ Map.Entry<GirlFriend, String>ent=it.next(); System.out.println(ent.getKey()+"\t"+ent.getValue()); } } }
Map集合的用法 随笔 第6张 Map集合的用法 随笔 第7张
public class Demo03 { public static void main(String[] args) { Map<GirlFriend,String>map=new HashMap<GirlFriend,String>(); //创建对象 GirlFriend g1=new GirlFriend("吴宣仪",24,166); GirlFriend g2=new GirlFriend("杨超越",21,168); GirlFriend g3=new GirlFriend("朴孝敏",28,167); GirlFriend g4=new GirlFriend("罗玉凤",34,165); //向map集合中添加key和value map.put(g1, "张三"); map.put(g2, "李四"); map.put(g3, "王五"); map.put(g4, "李四"); //KeySet+for Set<GirlFriend>set=map.keySet(); for(GirlFriend g:set){ System.out.println(g+"\t"+map.get(g)); } System.out.println("==================================================="); //KeySet+iterator Iterator<GirlFriend>it=set.iterator(); while(it.hasNext()){ GirlFriend gg=it.next(); System.out.println(gg+"\t"+map.get(gg)); } } }
Map集合的用法 随笔 第8张
扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄