黑马程序员--集合Map用法小结与练习

--------- android培训java培训期待与您交流 ---------

5 Map集合学习与小练习

5.1 Map集合知识点

 

Map集合:该集合存储键值对。一对一对往里存。而且要保证键的唯一性。
 1,添加。
  put(K key, V value) 向集合中添加新的映射关系
  putAll(Map<? extends K,? extends V> m) 把指定映射关系集合复制到该集合中

 

 2,删除。
  clear() 删除所有映射关系
  remove(Object key) 如果存在于该键相对应的映射关系,则删除该映射关系。

 

 3,判断。
  containsValue(Object value) 如果此映射包含指定键的映射关系,则返回 true
  containsKey(Object key) 如果此映射将一个或多个键映射到指定值,则返回 true
  isEmpty() 如果此映射未包含键-值映射关系,则返回 true

 


 4,获取。
  get(Object key) 返回指定键所映射的值;如果此映射不包含该键的映射关系,则返回 null
  size()      返回此映射中的键-值映射关系数。
  values()     返回此映射中包含的值的 Collection 视图。

 

  entrySet()   返回此映射中包含的映射关系的 Set 视图。
  keySet()   返回此映射中包含的键的 Set 视图。

 

Map:注意Hashtable和HashMap的区别(红色部分)
 |--Hashtable:底层是哈希表数据结构,不可以存入null键null值。该集合是线程同步的。jdk1.0.效率低。
 |--HashMap:底层是哈希表数据结构,允许使用 null 值和 null 键,该集合是不同步的。将hashtable替代,jdk1.2.效率高。
 |--TreeMap:底层是二叉树数据结构。线程不同步。可以用于给map集合中的键进行排序。

 

和Set很像。其实,Set底层就是使用了Map集合

5,Map集合基本应用示例

 

MapDemo
 1 package Map;
 2 
 3 import java.util.*;
 4 class  MapDemo
 5 {
 6     public static void main(String[] args) 
 7     {
 8         Map<String,String> map = new HashMap<String,String>();
 9         Map<String,String> map1=new HashMap<String,String>();
10         
11         //添加元素,如果出现添加时,相同的键。那么后添加的值会覆盖原有键对应值。
12         //并且put方法会返回被覆盖的值。
13         System.out.println("put:"+map.put("01","zhangsan1"));
14         System.out.println("put:"+map.put("01","wnagwu"));
15         map.put("02","zhangsan2");
16         map.put("03","zhangsan3");
17         map1.put("05", "zhangsan4");
18         map1.put("06", "zhangsan6");
19 
20         System.out.println("containsKey:"+map.containsKey("022"));
21         //System.out.println("remove:"+map.remove("02"));
22 
23         System.out.println("get:"+map.get("023"));
24 
25         map.put("04",null);
26         System.out.println("get:"+map.get("04"));
27         //可以通过get方法的返回值来判断一个键是否存在。通过返回null来判断。
28 
29     
30         //获取map集合中所有的值。
31         Collection<String> coll = map.values();
32         int len=map.size();
33         System.out.println(coll);
34         System.out.println(len);
35         System.out.println(map);
36         System.out.println(map1);
37         //将map1集合全部映射到map集合中
38         map.putAll(map1);
39         System.out.println(map);
40     }
41 }

 

5.2 Map集合的两种取出方式

1,Set<k> keySet:将map中所有的键存入到Set集合。因为set具备迭代器。
 所以可以用迭代方式取出所有的键,在根据get方法。获取每一个键对应的值。
  

 Map集合的取出原理:将map集合转成set集合。在通过迭代器取出。


2,Set<Map.Entry<k,v>> entrySet:将map集合中的映射关系存入到了set集合中,
    而这个关系的数据类型就是:Map.Entry

    Entry其实就是Map中的一个static内部接口。
    为什么要定义在内部呢?
    因为只有有了Map集合,有了键值对,才会有键值的映射关系。
    关系属于Map集合中的一个内部事物。
    而且该事物在直接访问Map集合中的元素。

 

 

两种取出方式示例
 1 import java.util.*;
 2 
 3 
 4 class MapDemo2 
 5 {
 6     public static void main(String[] args) 
 7     {
 8         Map<String,String> map = new HashMap<String,String>();
 9 
10         map.put("02","zhangsan2");
11         map.put("03","zhangsan3");
12         map.put("01","zhangsan1");
13         map.put("04","zhangsan4");
14 
15         
16         //方式一:先获取map集合的所有键的Set集合,keySet();
17         Set<String> keySet = map.keySet();
18 
19         //有了Set集合。就可以获取其迭代器。
20         Iterator<String> it = keySet.iterator();
21 
22         while(it.hasNext())
23         {
24             String key = it.next();
25             //有了键可以通过map集合的get方法获取其对应的值。
26             String value  = map.get(key);
27             System.out.println("key:"+key+",value:"+value);
28         }
29 
30         
31         //方式二:将Map集合中的映射关系取出。存入到Set集合中。
32         Set<Map.Entry<String,String>> entrySet = map.entrySet();
33 
34         Iterator<Map.Entry<String,String>> it1 = entrySet.iterator();
35 
36         while(it1.hasNext())
37         {
38             Map.Entry<String,String> me = it1.next();
39             String key = me.getKey();
40             String value = me.getValue();
41 
42             System.out.println(key+":"+value);
43 
44         }
45     }
46 }

 

 

 

3,Map扩展知识

Map集合被使用是因为具备映射关系。现实生活中但大多数关系都是映射关系,所以Map集合被广泛使用。

现已传智播客为例,传智播客是个IT培训结构,这个培训结构有很多的班级,每个班级又有很多学生,

传智播客-----班级, 班级------学生这两组关系都是映射关系

加入有预热班和就业班两个班级,怎样应用映射关系来

 

Map集合应用示例
 1 package Map;
 2 
 3 /*
 4 map扩展知识。
 5 
 6 map集合被使用是因为具备映射关系。
 7 
 8 "yureban"   Student("01" "zhangsan");
 9 
10 "yureban" Student("02" "lisi");
11 
12 "jiuyeban" "01" "wangwu";
13 "jiuyeban" "02" "zhaoliu";
14 
15 一个学校有多个教室。每一个教室都有名称。
16 
17 
18 */
19 import java.util.*;
20 
21 class Student
22 {
23     private String id;
24     private String name;
25     Student(String id,String name)
26     {
27         this.id = id;
28         this.name = name;
29     }
30     public String toString()
31     {
32         return id+":::"+name;
33     }
34 }
35 class  MapDemo3
36 {
37 
38     public static void demo()
39     {
40         HashMap<String,List<Student>> czbk = new HashMap<String,List<Student>>();
41 
42         List<Student> reyu = new ArrayList<Student>();
43         List<Student> jiuye = new ArrayList<Student>();
44 
45         czbk.put("yureban",reyu);
46         czbk.put("jiuyeban",jiuye);
47 
48         reyu.add(new Student("01","zhagnsa"));
49         reyu.add(new Student("04","wangwu"));
50         jiuye.add(new Student("01","zhouqi"));
51         jiuye.add(new Student("02","zhaoli"));
52 
53 
54         Iterator<String> it = czbk.keySet().iterator();
55 
56         while(it.hasNext())
57         {
58             String roomName = it.next();
59             List<Student> room = czbk.get(roomName);
60             
61             System.out.println(roomName);
62             getInfos(room);
63         }
64 
65     }
66     public static void getInfos(List<Student> list)
67     {
68         Iterator<Student> it = list.iterator();
69         while(it.hasNext())
70         {
71             Student s = it.next();
72             System.out.println(s);
73         }
74     }
75 
76 
77     public static void main(String[] args) 
78     {
79          demo();
80             
81     }
82     /**
83      * 根据学生所在的班级来获得学生的信息
84      * @param roomMap
85      */
86     public static void getStudentInfo(HashMap<String,String> roomMap)
87     {
88         Iterator<String> it = roomMap.keySet().iterator();
89 
90         while(it.hasNext())
91         {
92             String id = it.next();
93             String name = roomMap.get(id);
94             System.out.println(id+":"+name);
95         }
96     }
97 }

 

5.3 Map集合练习

 

练习一:

每一个学生都有对应的归属地。
学生Student,地址String。
学生属性:姓名,年龄。
注意:姓名和年龄相同的视为同一个学生。
保证学生的唯一性。

 

思路:
1,描述学生。

 

2,定义map容器。将学生作为键,地址作为值。存入。

 

3,获取map集合中的元素。

 

 

MapTest
 1 import java.util.*;
 2 class Student implements Comparable<Student>
 3 {
 4     private String name;
 5     private int age;
 6     Student(String name,int age)
 7     {
 8         this.name = name;
 9         this.age = age;
10     }
11     
12     public int compareTo(Student s)
13     {
14         int num = new Integer(this.age).compareTo(new Integer(s.age));
15 
16         if(num==0)
17             return this.name.compareTo(s.name);
18         return num;
19     }
20 
21     public int hashCode()
22     {
23         return name.hashCode()+age*34;
24     }
25     public boolean equals(Object obj)
26     {
27         if(!(obj instanceof Student))
28             throw new ClassCastException("类型不匹配");
29 
30         Student s = (Student)obj;
31 
32         return this.name.equals(s.name) && this.age==s.age;
33         
34 
35     }
36     public void setName(String name){
37         this.name=name;
38     }
39     public String getName()
40     {
41         return name;
42     }
43     public void setAge(int age)
44     {
45         this.age=age;
46     }
47     public int getAge()
48     {
49         return age;
50     }
51     public String toString()
52     {
53         return name+":"+age;
54     }
55 }
56 
57 
58 
59 class  MapTest
60 {
61     public static void main(String[] args) 
62     {
63         HashMap<Student,String> hm = new HashMap<Student,String>();
64 
65         hm.put(new Student("lisi1",21),"beijing");
66         hm.put(new Student("lisi1",21),"tianjin");
67         hm.put(new Student("lisi2",22),"shanghai");
68         hm.put(new Student("lisi3",23),"nanjing");
69         hm.put(new Student("lisi4",24),"wuhan");
70 
71         //第一种取出方式 keySet
72 
73         Set<Student> keySet = hm.keySet();
74 
75         Iterator<Student> it = keySet.iterator();
76 
77         while(it.hasNext())
78         {
79             Student stu = it.next();
80             String addr = hm.get(stu);
81             System.out.println(stu+".."+addr);
82         }
83 
84 
85         //第二种取出方式 entrySet
86         Set<Map.Entry<Student,String>> entrySet = hm.entrySet();
87 
88         Iterator<Map.Entry<Student,String>> iter = entrySet.iterator();
89         
90         while(iter.hasNext())
91         {
92             Map.Entry<Student,String> me = iter.next();
93             Student stu = me.getKey();
94             String addr = me.getValue();
95             System.out.println(stu+"........."+addr);
96         }
97     }
98 }

 

练习二:

需求:对学生对象的年龄进行升序排序。

因为数据是以键值对形式存在的。
所以要使用可以排序的Map集合。TreeMap。

Student类与练习一相同,代码不再重复

 

 

MapTest2
 1 import java.util.*;
 2 
 3 class StuNameComparator implements Comparator<Student>
 4 {
 5     public int compare(Student s1,Student s2)
 6     {
 7         int num = s1.getName().compareTo(s2.getName());
 8         if(num==0)
 9             return new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
10 
11         return num;
12     }
13 }
14 
15 
16 class  MapTest2
17 {
18     public static void main(String[] args) 
19     {
20         TreeMap<Student,String> tm = new TreeMap<Student,String>(new StuNameComparator());
21 
22         tm.put(new Student("blisi3",23),"nanjing");
23         tm.put(new Student("lisi1",21),"beijing");
24         tm.put(new Student("alisi4",24),"wuhan");
25         tm.put(new Student("lisi1",21),"tianjin");
26         tm.put(new Student("lisi2",22),"shanghai");
27 
28         
29         Set<Map.Entry<Student,String>> entrySet = tm.entrySet();
30 
31         Iterator<Map.Entry<Student,String>> it = entrySet.iterator();
32 
33         while(it.hasNext())
34         {
35             Map.Entry<Student,String> me = it.next();
36 
37             Student stu = me.getKey();
38             String addr = me.getValue();
39             System.out.println(stu+":::"+addr);
40         }
41     }
42 }

 

练习三:

 

 

"sdfgzxcvasdfxcvdf"获取该字符串中的字母出现的次数。

 

希望打印结果:a(1)c(2).....

 

首先,审题发现,每个字母都有一定的次数相对应,构成了映射关系,因此可以选择具有映射关系的Map集合。

也就是说,当数据之间存在这映射关系时,就要先想到用Map集合。

其次,思路如下:

 

1)将字符串转换成字符数组。因为要对每一个字母进行操作。

 

2)定义一个map集合,因为打印结果的字母有顺序,所以使用treemap集合。

 

3)遍历字符数组。
 将每一个字母作为键去查map集合。
 如果返回null,将该字母和1存入到map集合中。
 如果返回不是null,说明该字母在map集合已经存在并有对应次数。
 那么就获取该次数并进行自增。,然后将该字母和自增后的次数存入到map集合中。覆盖掉用原来键所对应的值。

 

4)将map集合中的数据变成指定的字符串形式返回。

程序如下所示:

MapTest3
 1 import java.util.*;
 2 class  MapTest3
 3 {
 4     public static void main(String[] args) 
 5     {
 6         String s= charCount("ak+abAf1c,dCkaAbc-defa");
 7         System.out.println(s);
 8     }
 9     
10     public static String charCount(String str)
11     {
12         char[] chs = str.toCharArray();
13 
14         TreeMap<Character,Integer> tm = new TreeMap<Character,Integer>();
15 
16         
17         int count = 0;
18         for(int x=0; x<chs.length; x++)
19         {
20             
21 
22             if(!(chs[x]>='a' && chs[x]<='z' || chs[x]>='A' && chs[x]<='Z'))
23                 continue;
24             
25             //返回值
26             Integer value = tm.get(chs[x]);
27 
28             
29             if(value!=null)
30                 count = value;
31             count++;
32             tm.put(chs[x],count);//直接往集合中存储字符和数字,为什么可以,因为自动装箱。
33 
34             count = 0;
35             /*
36             if(value==null)
37             {
38                 tm.put(chs[x],1);
39             }
40             else
41             {
42                 value = value + 1;
43                 tm.put(chs[x],value);
44             }
45             */
46 
47         }
48 
49         //System.out.println(tm);
50 
51         StringBuilder sb = new StringBuilder();
52 
53         Set<Map.Entry<Character,Integer>> entrySet = tm.entrySet();
54         Iterator<Map.Entry<Character,Integer>>  it = entrySet.iterator();
55 
56         while(it.hasNext())
57         {
58             Map.Entry<Character,Integer> me = it.next();
59             Character ch = me.getKey();
60             Integer value = me.getValue();
61             sb.append(ch+"("+value+")");
62         }
63 
64 
65         return sb.toString();
66     }
67 
68 }

 

 

--------- android培训java培训期待与您交流 --------详细请查看:http://edu.csdn.net/heima/

posted on 2012-08-05 17:19  doublewinwin  阅读(344)  评论(0编辑  收藏  举报