Map

Map集合

概述

  • Map集合概述

    interface Map<K,V>  K:键的类型;V:值的类型
    
  • Map集合的特点

    • 键值对映射关系,一个键对应一个值
    • 键不能重复,值可以重复
    • 元素存取无序
  • Map集合的基本使用

    public class MapDemo01 {
        public static void main(String[] args) {
            //创建集合对象
            Map<String,String> map = new HashMap<String,String>();
    
            //V put(K key, V value) 将指定的值与该映射中的指定键相关联
            map.put("itheima001","林青霞");
            map.put("itheima002","张曼玉");
            map.put("itheima003","王祖贤");
            map.put("itheima003","柳岩");//新的值柳岩将覆盖王祖贤
    
            //输出集合对象
            System.out.println(map);
        }
    }
    /*console:
    {itheima003=柳岩, itheima001=林青霞, itheima002=张曼玉}
    /
    

常用方法

方法介绍

方法名 说明
V put(K key,V value) 添加元素
V remove(Object key) 根据键删除键值对元素
void clear() 移除所有的键值对元素
boolean containsKey(Object key) 判断集合是否包含指定的键
boolean containsValue(Object value) 判断集合是否包含指定的值
boolean isEmpty() 判断集合是否为空
int size() 集合的长度,也就是集合中键值对的个数
V get(Object key) 根据键获取值
Set keySet() 获取所有键的集合
Collection values() 获取所有值的集合
Set<Map.Entry<K,V>> entrySet() 获取所有键值对对象的集合
public class MapDemo02 {
    public static void main(String[] args) {
        //创建集合对象
        Map<String,String> map = new HashMap<String,String>();

        //V put(K key,V value):添加元素
        map.put("张无忌","赵敏");
        map.put("郭靖","黄蓉");
        map.put("杨过","小龙女");

        //V remove(Object key):根据键删除键值对元素
//        System.out.println(map.remove("郭靖"));
//        System.out.println(map.remove("郭襄"));
       
        //V get(Object key):根据键获取值
//        System.out.println(map.get("张无忌"));

        //void clear():移除所有的键值对元素
//        map.clear();

        //boolean containsKey(Object key):判断集合是否包含指定的键
//        System.out.println(map.containsKey("郭靖"));
//        System.out.println(map.containsKey("郭襄"));

        //boolean isEmpty():判断集合是否为空
//        System.out.println(map.isEmpty());
        
		//Set<K> keySet():获取所有键的集合
//        Set<String> keySet = map.keySet();
//        for(String key : keySet) {
//            System.out.println(key);
//        }
        
        //Collection<V> values():获取所有值的集合
        Collection<String> values = map.values();
        for(String value : values) {
            System.out.println(value);
        }        
        
        //int size():集合的长度,也就是集合中键值对的个数
        System.out.println(map.size());

        //输出集合对象
        System.out.println(map);
    }
}

Map集合的遍历

  • 方法一:通过keySet得到所有key的集合,然后通过get方法得到key对应的value。
public class MapDemo01 {
    public static void main(String[] args) {
        //创建集合对象
        Map<String, String> map = new HashMap<String, String>();

        //添加元素
        map.put("张无忌", "赵敏");
        map.put("郭靖", "黄蓉");
        map.put("杨过", "小龙女");

        //获取所有键的集合。用keySet()方法实现
        Set<String> keySet = map.keySet();
        //遍历键的集合,获取到每一个键。用增强for实现
        for (String key : keySet) {
            //根据键去找值。用get(Object key)方法实现
            String value = map.get(key);
            System.out.println(key + "," + value);
        }
    }
}
  • 方法二:通过entrySet方法获取每一个键值对,Map.EntrySet<K,V>是定义在Map中的一个内部接口,代表键值对。
public class MapDemo02 {
    public static void main(String[] args) {
        //创建集合对象
        Map<String, String> map = new HashMap<String, String>();

        //添加元素
        map.put("张无忌", "赵敏");
        map.put("郭靖", "黄蓉");
        map.put("杨过", "小龙女");

        //获取所有键值对对象的集合
        Set<Map.Entry<String, String>> entrySet = map.entrySet();
        //遍历键值对对象的集合,得到每一个键值对对象
        for (Map.Entry<String, String> me : entrySet) {
            //根据键值对对象获取键和值
            String key = me.getKey();
            String value = me.getValue();
            System.out.println(key + "," + value);
        }
    }
}

Map集合的案例

HashMap集合练习之键是String值是Student

  • 案例需求

    ​ 创建一个HashMap集合,键是学号(String),值是学生对象(Student)。存储三个键值对元素,并遍历

  • 代码实现

    • 学生类

      public class Student {
          private String name;
          private int age;
      
          public Student() {
          }
      
          public Student(String name, int age) {
              this.name = name;
              this.age = age;
          }
      
          public String getName() {
              return name;
          }
      
          public void setName(String name) {
              this.name = name;
          }
      
          public int getAge() {
              return age;
          }
      
          public void setAge(int age) {
              this.age = age;
          }
      }
      
    • 测试类

      /*
          需求:
              创建一个HashMap集合,键是学号(String),值是学生对象(Student)。存储三个键值对元素,并遍历
      
          思路:
              1:定义学生类
              2:创建HashMap集合对象
              3:创建学生对象
              4:把学生添加到集合
              5:遍历集合
                  方式1:键找值
                  方式2:键值对对象找键和值
       */
      public class HashMapDemo {
          public static void main(String[] args) {
              //创建HashMap集合对象
              HashMap<String, Student> hm = new HashMap<String, Student>();
      
              //创建学生对象
              Student s1 = new Student("林青霞", 30);
              Student s2 = new Student("张曼玉", 35);
              Student s3 = new Student("王祖贤", 33);
      
              //把学生添加到集合
              hm.put("itheima001", s1);
              hm.put("itheima002", s2);
              hm.put("itheima003", s3);
      
              //方式1:键找值
              Set<String> keySet = hm.keySet();
              for (String key : keySet) {
                  Student value = hm.get(key);
                  System.out.println(key + "," + value.getName() + "," + value.getAge());
              }
              System.out.println("--------");
      
              //方式2:键值对对象找键和值
              Set<Map.Entry<String, Student>> entrySet = hm.entrySet();
              for (Map.Entry<String, Student> me : entrySet) {
                  String key = me.getKey();
                  Student value = me.getValue();
                  System.out.println(key + "," + value.getName() + "," + value.getAge());
              }
          }
      }
      

HashMap集合练习之键是Student值是String

  • 案例需求

    • 创建一个HashMap集合,键是学生对象(Student),值是居住地 (String)。存储多个元素,并遍历。
    • 要求保证键的唯一性:如果学生对象的成员变量值相同,我们就认为是同一个对象
  • 代码实现

    • 学生类

      public class Student {
          private String name;
          private int age;
      
          public Student() {
          }
      
          public Student(String name, int age) {
              this.name = name;
              this.age = age;
          }
      
          public String getName() {
              return name;
          }
      
          public void setName(String name) {
              this.name = name;
          }
      
          public int getAge() {
              return age;
          }
      
          public void setAge(int age) {
              this.age = age;
          }
      	
          //现在的键是学生类对象,这种自定义的类必须重写hashCode方法和equals方法,确保唯一性
          @Override
          public boolean equals(Object o) {
              if (this == o) return true;
              if (o == null || getClass() != o.getClass()) return false;
      
              Student student = (Student) o;
      
              if (age != student.age) return false;
              return name != null ? name.equals(student.name) : student.name == null;
          }
      
          @Override
          public int hashCode() {
              int result = name != null ? name.hashCode() : 0;
              result = 31 * result + age;
              return result;
          }
      }
      
    • 测试类

      public class HashMapDemo {
          public static void main(String[] args) {
              //创建HashMap集合对象
              HashMap<Student, String> hm = new HashMap<Student, String>();
      
              //创建学生对象
              Student s1 = new Student("林青霞", 30);
              Student s2 = new Student("张曼玉", 35);
              Student s3 = new Student("王祖贤", 33);
              Student s4 = new Student("王祖贤", 33);
      
              //把学生添加到集合
              hm.put(s1, "西安");
              hm.put(s2, "武汉");
              hm.put(s3, "郑州");
              hm.put(s4, "北京");
      
              //遍历集合
              Set<Student> keySet = hm.keySet();
              for (Student key : keySet) {
                  String value = hm.get(key);
                  System.out.println(key.getName() + "," + key.getAge() + "," + value);
              }
          }
      }
      

集合嵌套之ArrayList嵌套HashMap

  • 案例需求

    • 创建一个ArrayList集合,存储三个元素,每一个元素都是HashMap
    • 每一个HashMap的键和值都是String,并遍历。
  • 代码实现

    public class ArrayListIncludeHashMapDemo {
        public static void main(String[] args) {
            //创建ArrayList集合
            ArrayList<HashMap<String, String>> array = new ArrayList<HashMap<String, String>>();
    
            //创建HashMap集合,并添加键值对元素
            HashMap<String, String> hm1 = new HashMap<String, String>();
            hm1.put("孙策", "大乔");
            hm1.put("周瑜", "小乔");
            //把HashMap作为元素添加到ArrayList集合
            array.add(hm1);
    
            HashMap<String, String> hm2 = new HashMap<String, String>();
            hm2.put("郭靖", "黄蓉");
            hm2.put("杨过", "小龙女");
            //把HashMap作为元素添加到ArrayList集合
            array.add(hm2);
    
            HashMap<String, String> hm3 = new HashMap<String, String>();
            hm3.put("令狐冲", "任盈盈");
            hm3.put("林平之", "岳灵珊");
            //把HashMap作为元素添加到ArrayList集合
            array.add(hm3);
    
            //遍历ArrayList集合
            for (HashMap<String, String> hm : array) {
                Set<String> keySet = hm.keySet();
                for (String key : keySet) {
                    String value = hm.get(key);
                    System.out.println(key + "," + value);
                }
            }
        }
    }
    

集合嵌套之HashMap嵌套ArrayList

  • 案例需求

    • 创建一个HashMap集合,存储三个键值对元素,每一个键值对元素的键是String,值是ArrayList
    • 每一个ArrayList的元素是String,并遍历。
  • 代码实现

    public class HashMapIncludeArrayListDemo {
        public static void main(String[] args) {
            //创建HashMap集合
            HashMap<String, ArrayList<String>> hm = new HashMap<String, ArrayList<String>>();
    
            //创建ArrayList集合,并添加元素
            ArrayList<String> sgyy = new ArrayList<String>();
            sgyy.add("诸葛亮");
            sgyy.add("赵云");
            //把ArrayList作为元素添加到HashMap集合
            hm.put("三国演义",sgyy);
    
            ArrayList<String> xyj = new ArrayList<String>();
            xyj.add("唐僧");
            xyj.add("孙悟空");
            //把ArrayList作为元素添加到HashMap集合
            hm.put("西游记",xyj);
    
            ArrayList<String> shz = new ArrayList<String>();
            shz.add("武松");
            shz.add("鲁智深");
            //把ArrayList作为元素添加到HashMap集合
            hm.put("水浒传",shz);
    
            //遍历HashMap集合
            Set<String> keySet = hm.keySet();
            for(String key : keySet) {
                System.out.println(key);
                ArrayList<String> value = hm.get(key);
                for(String s : value) {
                    System.out.println("\t" + s);
                }
            }
        }
    }
    

统计字符串中每个字符出现的次数

  • 案例需求

    • 键盘录入一个字符串,要求统计字符串中每个字符串出现的次数。
    • 举例:键盘录入“aababcabcdabcde” 在控制台输出:“a(5)b(4)c(3)d(2)e(1)”
  • 代码实现

    public class HashMapDemo {
        public static void main(String[] args) {
            //键盘录入一个字符串
            Scanner sc = new Scanner(System.in);
            System.out.println("请输入一个字符串:");
            String line = sc.nextLine();
    
            //创建HashMap集合,键是Character,值是Integer
    //        HashMap<Character, Integer> hm = new HashMap<Character, Integer>();
            TreeMap<Character, Integer> hm = new TreeMap<Character, Integer>();
    
            //遍历字符串,得到每一个字符
            for (int i = 0; i < line.length(); i++) {
                char key = line.charAt(i);
    
                //拿得到的每一个字符作为键到HashMap集合中去找对应的值,看其返回值
                Integer value = hm.get(key);
    
                if (value == null) {
                    //如果返回值是null:说明该字符在HashMap集合中不存在,就把该字符作为键,1作为值存储
                    hm.put(key,1);
                } else {
                    //如果返回值不是null:说明该字符在HashMap集合中存在,把该值加1,然后重新存储该字符和对应的值
                    value++;
                    hm.put(key,value);
                }
            }
    
            //遍历HashMap集合,得到键和值,按照要求进行拼接
            StringBuilder sb = new StringBuilder();
    
            Set<Character> keySet = hm.keySet();
            for(Character key : keySet) {
                Integer value = hm.get(key);
                sb.append(key).append("(").append(value).append(")");
            }
    
            String result = sb.toString();
    
            //输出结果
            System.out.println(result);
        }
    }
    

Properties

Map接口中还有一个实现类Hashtable,它和HashMap十分相似,区别在于Hashtable是线程安全的。Hashtable存取元素时速度很慢,目前基本上被HashMap类所取代,但Hashtable类有一个子类Properties非常重要。Properties主要用来存储字符串类型的键和值,在实际开发中,经常使用Properties集合来存取应用的配置项。
详见IO流。

posted @ 2021-08-29 11:07  黄了的韭菜  阅读(105)  评论(0编辑  收藏  举报