首页 > 技术文章 > 集合之六:Map接口

lotus-wmm 2018-02-13 22:55 原文

Map接口概述

  Map接口中的集合和Collection接口中的集合在存储数据的格式上有很大的不同,Map接口下的内容是以<K , V> ,键值对的形式存储的,我们查询API,Map接口的描述是:

  将键映射到值的对象。一个映射不能包含重复的键每个键最多只能映射到一个值。 

Map接口常用实现类:

  • HashMap
    • 无序,键不可重复
    • 键和值都允许使用null 
  • LInkedHashMap
    • 线程不安全
    • 使用双向链表来维护key-value对的次序,该链表定义了迭代顺序,该迭代顺序与key-value对的插入顺序保持一致。
  • HashTable
    • 线程安全
    • 不容许使用null作为key和value
    • 不常用,现已被Properties类代替

Map的常用方法

  

 1 package com.shsxt.lisa;
 2 
 3 import java.util.Collection;
 4 import java.util.HashMap;
 5 import java.util.Map;
 6 
 7 /*
 8  * Map接口中的常用方法
 9  *         使用Map接口的实现类 HashMap
10  */
11 public class MapDemo01 {
12 
13     public static void main(String[] args) {
14         
15         function2();
16         
17     }
18     
19     
20     /*
21      * put(K,V)   ---> 将键值对存储到集合中
22      * 返回值: 一般情况下 返回值是null,当储存重复键时 会返回被覆盖的值
23      */
24     public static void function() {
25         //
26         Map<String,Integer> map = new HashMap<>();
27         map.put("张二狗", 12);
28         map.put("zhang",13);
29         //有重复键时 后者会将前者覆盖
30         int i=map.put("zhang",2);
31         System.out.println(i);//当储存重复键时 会返回被覆盖的值
32         
33     }
34     
35     /*
36      * get(K)   ---> 通过键取对应的值
37      * 返回值: 一般情况下 返回值是null,当储存重复键时 会返回被覆盖的值
38      */
39     public static void function1() {
40         Map<Integer, String> map=new HashMap<>();
41         map.put(1, "张三丰");
42         map.put(2, "张二二");
43         map.put(3, "张思思");
44         
45         //
46         String string = map.get(5);
47         //如果集合中没有这个键 方法返回空
48         System.out.println(string);
49     }
50     
51     /*
52      * 移除集合中的键值对
53      * remove(K)---->返回  V
54      */
55     
56     public static void function2() {
57         Map<Integer, String> map=new HashMap<>();
58         map.put(1, "张三丰");
59         map.put(2, "张二二");
60         map.put(3, "张思思");
61         
62         //返回被删掉的值
63         String string = map.remove(1);
64         //如果集合中没有这个键 方法返回空
65         System.out.println(string);
66     }
67 }

Map集合遍历的方式

  1. entrySet方法 键值对的映射关系(Entry键值对对象) 获取
  2. 通过keySet() 方法 获取Map集合中所有的键,由于键是唯一的,所以返回一个Set集合存储所有的键

     1 import java.util.HashMap;
     2 import java.util.Iterator;
     3 import java.util.Map;
     4 
     5 public class TestMap {
     6     public static void main(String[] args) {
     7         Map<Integer, String> map = new HashMap<Integer, String>();
     8         map.put(1, "a");
     9         map.put(2, "b");
    10         map.put(3, "ab");
    11         map.put(4, "ab");
    12         map.put(4, "ab");// 和上面相同 , 会自己筛选
    13         System.out.println(map.size());
    14         // 第一种:
    15         /*
    16          * Set<Integer> set = map.keySet(); //得到所有key的集合
    17          * 
    18          * for (Integer in : set) { String str = map.get(in);
    19          * System.out.println(in + "     " + str); }
    20          */
    21         System.out.println("第一种:通过Map.keySet遍历key和value:");
    22         for (Integer in : map.keySet()) {
    23             //map.keySet()返回的是所有key的值
    24             String str = map.get(in);//得到每个key多对用value的值
    25             System.out.println(in + "     " + str);
    26         }
    27         // 第二种:
    28         System.out.println("第二种:通过Map.entrySet使用iterator遍历key和value:");
    29         Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();
    30         while (it.hasNext()) {
    31              Map.Entry<Integer, String> entry = it.next();
    32                System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
    33         }
    34         // 第三种:推荐,尤其是容量大时
    35         System.out.println("第三种:通过Map.entrySet遍历key和value");
    36         for (Map.Entry<Integer, String> entry : map.entrySet()) {
    37             //Map.entry<Integer,String> 映射项(键-值对)  有几个方法:用上面的名字entry
    38             //entry.getKey() ;entry.getValue(); entry.setValue();
    39             //map.entrySet()  返回此映射中包含的映射关系的 Set视图。
    40             System.out.println("key= " + entry.getKey() + " and value= "
    41                     + entry.getValue());
    42         }
    43         // 第四种:
    44         System.out.println("第四种:通过Map.values()遍历所有的value,但不能遍历key");
    45         for (String v : map.values()) {
    46             System.out.println("value= " + v);
    47         }
    48     }
    49 }

     

练习题

1.分析以下需求,并用代码实现:
(1)定义一个学生类Student,包含属性:姓名(String name)、年龄(int age)
(2)定义Map集合,用Student对象作为key,用字符串(此表示表示学生的住址)作为value
(3)利用四种方式遍历Map集合中的内容,格式:key::value

 1 package com.shsxt.homework;
 2 
 3 import java.util.HashMap;
 4 import java.util.Iterator;
 5 import java.util.Map;
 6 import java.util.Map.Entry;
 7 import java.util.Set;
 8 
 9 /*
10  * 1.分析以下需求,并用代码实现:
11     (1)定义一个学生类Student,包含属性:姓名(String name)、年龄(int age)
12     (2)定义Map集合,用Student对象作为key,用字符串(此表示表示学生的住址)作为value
13     (3)利用四种方式遍历Map集合中的内容,格式:key::value
14  */
15 public class Homework01 {
16     
17     public static void main(String[] args) {
18         Map<Student,String> map = new HashMap<>();
19         map.put(new Student("张二狗",12),"大理国内的村子");
20         map.put(new Student("元首",10),"啦啦啦德玛西亚");
21         map.put(new Student("BigBean",23),"克苏鲁大陆");
22         
23         
24         //1 keyset
25         Set<Student> set=map.keySet();
26         for(Student s : set){
27             System.out.println(s+"::"+map.get(s));
28         }
29         System.out.println("-------------");
30         
31         //2 entry
32         Set<Entry<Student, String>> entrySet = map.entrySet();
33         Iterator<Entry<Student, String>> it=entrySet.iterator();
34         while(it.hasNext()){
35             Entry<Student, String> entry= it.next();
36             System.out.println(entry.getKey()+"::"+entry.getValue());
37         }
38         
39         
40         System.out.println("-------------");
41         //第三种 :推荐  尤其是容量大时
42         System.out.println("第三种:通过Map.entrySet遍历key和value");
43         for(Map.Entry<Student, String> entry:map.entrySet()){
44             System.out.println(entry.getKey()+"::"+entry.getValue());
45         }
46         
47         System.out.println("-------------");
48         // 第四种:
49         System.out.println("第四种:通过Map.values()遍历所有的value,但不能遍历key");
50         for(String string:map.values()){
51             System.out.println("value = "+ string);
52         }
53     }
54     
55     
56 }
57 class Student{
58     
59     private String name;
60     
61     private int age;
62 
63     public String getName() {
64         return name;
65     }
66 
67     public void setName(String name) {
68         this.name = name;
69     }
70 
71     public int getAge() {
72         return age;
73     }
74 
75     public void setAge(int age) {
76         this.age = age;
77     }
78 
79     public Student(String name, int age) {
80         super();
81         this.name = name;
82         this.age = age;
83     }
84 
85     public Student() {
86         super();
87         // TODO Auto-generated constructor stub
88     }
89 
90     @Override
91     public String toString() {
92         return "Student [name=" + name + ", age=" + age + "]";
93     }
94     
95     
96 }

2.分析以下需求,并用代码实现:
(1)利用键盘录入,输入一个字符串
(2)统计该字符串中各个字符的数量
(3)如:
用户输入字符串"If~you-want~to~change-your_fate_I_think~you~must~come-to-the-dark-horse-to-learn-java"
程序输出结果:-(9)I(2)_(3)a(7)c(2)d(1)e(6)f(2)g(1)h(4)i(1)j(1)k(2)l(1)m(2)n(4)o(8)r(4)s(2)t(8)u(4)v(1)w(1)y(3)~(6)

 1 package com.shsxt.homework;
 2 
 3 import java.util.Map;
 4 import java.util.Scanner;
 5 import java.util.TreeMap;
 6 
 7 /*
 8  * 2.分析以下需求,并用代码实现:
 9     (1)利用键盘录入,输入一个字符串
10     (2)统计该字符串中各个字符的数量
11     (3)如:
12         用户输入字符串"If~you-want~to~change-your_fate_I_think~you~must~come-to-the-dark-horse-to-learn-java"
13         程序输出结果:-(9)I(2)_(3)a(7)c(2)d(1)e(6)f(2)g(1)h(4)i(1)j(1)k(2)l(1)m(2)n(4)o(8)r(4)s(2)t(8)u(4)v(1)w(1)y(3)~(6)
14  */
15 public class Homework02 {    
16     
17     public static void main(String[] args) {
18         Scanner sc  = new Scanner(System.in);
19         System.out.println("请输入字符串: ");
20         String str = sc.nextLine();
21         System.out.println("您输入的是: "+ str);
22         
23         
24         //String str="If~you-want~to~change-your_fate_I_think~you~must~come-to-the-dark-horse-to-learn-java";
25         //String str="Happy Happy";
26         char ch[]= new char[20];
27         ch=str.toCharArray();
28         String res=getTimes(str);
29         System.out.println(res);
30         
31     }
32     
33     public static String getTimes(String str){
34         //1 将字符串转成字符串数组
35         char ch[]=str.toCharArray();
36         //2 创建一个map\集合 将字符和出现的次数存储到集合中
37         Map<Character, Integer> map= new TreeMap<>();
38         //3 遍历字符数组
39         for(char c :ch){
40             map.put(c,map.get(c)!= null?map.get(c)+1:1);
41         }
42         //4 创建StringBuffer
43         StringBuffer sb = new StringBuffer();
44         //5 遍历map集合
45         for(Map.Entry<Character, Integer> entry : map.entrySet()){
46             sb.append(entry.getKey()).append("(").append(entry.getValue()).append(")");
47         }
48         //6 返回StirngBuffer
49         
50         return sb.toString();
51     }
52     
53 }

 

推荐阅读