1 Map接口概述
l Map中的集合,元素是成对存在的(理解为夫妻)。每个元素由键与值两部分组成,通过键可以找对所对应的值。
l Collection中的集合称为单列集合,Map中的集合称为双列集合。
l 需要注意的是,Map中的集合不能包含重复的键,值可以重复;每个键只能对应一个值。
Map中常用的集合为HashMap集合、LinkedHashMap集合。
Map集合的遍历:
1.keySet
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()));
}
}
2.entrySet
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()+" "+entry.getValue());
}
}
}
练习:
Iractor,for和entrySet,keySet遍历Map集合
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()+" "+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()+" "+ent.getValue());
}
}
}
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+" "+map.get(g));
}
System.out.println("===================================================");
//KeySet+iterator
Iterator<GirlFriend>it=set.iterator();
while(it.hasNext()){
GirlFriend gg=it.next();
System.out.println(gg+" "+map.get(gg));
}
}
}