Loading

Map集合概述


返回 我的技术栈(Technology Stack)



集合框架(Map集合概述和特点)


  • A:Map接口概述
    • 查看API可以知道:
      • 将键映射到值的对象
      • 一个映射不能包含重复的键
      • 每个键最多只能映射到一个值
  • B:Map接口和Collection接口的不同
    • Map是双列的,Collection是单列的
    • Map的键唯一,Collection的子体系Set是唯一的
    • Map集合的数据结构值针对键有效,跟值无关;Collection集合的数据结构是针对元素有效
    • set底层依赖map

集合框架(Map集合的功能概述)


  • A:Map集合的功能概述
    • a:添加功能

      • V put(K key,V value):添加元素。
        • 如果键是第一次存储,就直接存储元素,返回null

        • 如果键不是第一次存在,就用值把以前的值替换掉,返回以前的值

          import java.util.HashMap;
          import java.util.Map;

          public class Demo_map {

          public static void main(String[] args) {
          Map<String, Integer> map = new HashMap<>();
          Integer i1 = map.put("张三", 23);
          Integer i2 = map.put("李四", 24);
          Integer i3 = map.put("王五", 25);
          Integer i4 = map.put("赵六", 26);
          Integer i5 = map.put("张三", 26); //相同的键不存储,值覆盖,把被覆盖的值返回

          System.out.println(map);

          System.out.println(i1);
          System.out.println(i2);
          System.out.println(i3);
          System.out.println(i4);
          System.out.println(i5);

          }

          }
          输出:
          {李四=24, 张三=26, 王五=25, 赵六=26}
          null
          null
          null
          null
          23

    • b:删除功能

      • void clear():移除所有的键值对元素

      • V remove(Object key):根据键删除键值对元素,并把值返回

        import java.util.HashMap;
        import java.util.Map;

        public class Demo_map {

        public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();
        Integer i1 = map.put("张三", 23);
        Integer i2 = map.put("李四", 24);
        Integer i3 = map.put("王五", 25);
        Integer i4 = map.put("赵六", 26);

        Integer value = map.remove("张三");//根据键删除元素,返回键对应的值
        System.out.println(value);

        System.out.println(map);

        }

        }
        输出:
        23

    • c:判断功能

      • boolean containsKey(Object key):判断集合是否包含指定的键

      • boolean containsValue(Object value):判断集合是否包含指定的值

      • boolean isEmpty():判断集合是否为空

        import java.util.HashMap;
        import java.util.Map;

        public class Demo_map {

        public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();
        Integer i1 = map.put("张三", 23);
        Integer i2 = map.put("李四", 24);
        Integer i3 = map.put("王五", 25);
        Integer i4 = map.put("赵六", 26);

        System.out.println(map.containsKey("张三"));
        System.out.println(map.containsValue(100));

        }

        }
        输出:
        true
        false

    • d:获取功能

      • Set<Map.Entry<K,V>> entrySet():

      • V get(Object key):根据键获取值

      • Set keySet():获取集合中所有键的集合

      • Collection values():获取集合中所有值的集合

        import java.util.Collection;
        import java.util.HashMap;
        import java.util.Map;

        public class value {

        public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();
        Integer i1 = map.put("张三", 23);
        Integer i2 = map.put("李四", 24);
        Integer i3 = map.put("王五", 25);
        Integer i4 = map.put("赵六", 26);
        Integer i5 = map.put("张三", 26); //相同的键不存储,值覆盖,把被覆盖的值返回
        Collection c = map.values();
        System.out.println(c);
        System.out.println(map.size());

        }

        }
        输出:
        [24, 26, 25, 26]
        4

    • e:长度功能

      • int size():返回集合中的键值对的个数

集合框架(Map集合的遍历之键找值)


  • A:键找值思路:
    • 获取所有键的集合
    • 遍历键的集合,获取到每一个键
    • 根据键找值
  • B:案例演示
    • Map集合的遍历之键找值

      import java.util.HashMap;
      import java.util.Iterator;
      import java.util.Set;

      public class value {

      public static void main(String[] args) {
      HashMap<String, Integer> hm = new HashMap<>();
      hm.put("张三", 23);
      hm.put("李四", 24);
      hm.put("王五", 25);
      hm.put("赵六", 26);

      Set keySet = hm.keySet(); //获取集合中所有的键
      Iterator it = keySet.iterator(); //获取迭代器
      while(it.hasNext()) { //判断单列集合中是否有元素
      String key = it.next(); //获取集合中的每一个元素,其实就是双列集合中的键
      Integer value = hm.get(key); //根据键获取值
      System.out.println(key + "=" + value); //打印键值对
      }
      System.out.println("********************************");
      for(String key : hm.keySet()) { //增强for循环迭代双列集合第一种方式
      System.out.println(key + "=" + hm.get(key));
      }
      }

      }
      输出:
      李四=24
      张三=23
      王五=25
      赵六=26
      ********************************
      李四=24
      张三=23
      王五=25
      赵六=26

集合框架(Map集合的遍历之键值对对象找键和值)(推荐使用)


  • A:键值对对象找键和值思路:
    • 获取所有键值对对象的集合
    • 遍历键值对对象的集合,获取到每一个键值对对象
    • 根据键值对对象找键和值
  • B:案例演示
    • Map集合的遍历之键值对对象找键和值

      import java.util.HashMap;
      import java.util.Iterator;
      import java.util.Map;
      import java.util.Map.Entry;
      import java.util.Set;

      public class value {

      public static void main(String[] args) {
      HashMap<String, Integer> hm = new HashMap<>();
      hm.put("张三", 23);
      hm.put("李四", 24);
      hm.put("王五", 25);
      hm.put("赵六", 26);

      //Map.Entry说明Entry是Map的内部接口,将键和值封装成了Entry对象,并存储在set集合中
      Set<Map.Entry<String, Integer>> entrySet = hm.entrySet(); //获取所有的键值对象的集合
      Iterator<Entry<String, Integer>> it = entrySet.iterator();//获取迭代器
      while(it.hasNext()) {
      Entry<String, Integer> en = it.next(); //获取键值对对象
      String key = en.getKey(); //根据键值对对象获取键
      Integer value = en.getValue(); //根据键值对对象获取值
      System.out.println(key + "=" + value);
      }

      System.out.println("***************************");

      for(Entry<String,Integer> en : hm.entrySet()) {
      System.out.println(en.getKey() + "=" + en.getValue());
      }

      }
      }
      输出:
      李四=24
      张三=23
      王五=25
      赵六=26
      ***************************
      李四=24
      张三=23
      王五=25
      赵六=26

C:源码分析

集合框架(HashMap集合键是Student值是String的案例)


  • A:案例演示
    • HashMap集合键是Student值是String的案例

      package heima.map;
      public class Student {
      private String name;
      private int age;

      public Student() {
      }
      public Student(String name, int age) {
      this.name = name;
      this.age = age;
      }

      public void setName(String name) {
      this.name = name;
      }
      public String getName() {
      return name;
      }
      public void setAge(int age) {
      this.age = age;
      }
      public int getAge() {
      return age;
      }
      @Override
      public String toString() {
      return "Perosn [name = "+ name +" , age = "+ age +"]";
      }
      @Override
      public int hashCode(){
      final int prime = 31;
      int result = 1;
      result = prime * result + age;
      result = prime * result +((name == null) ? 0 : name.hashCode());
      return result;
      }
      public boolean equals(Object obj) {
      if (this == obj)
      return true;
      if (obj == null)
      return false;
      if(getClass() != obj.getClass())
      return false;
      Student other = (Student) obj;
      if (age != other.age)
      return false;
      if(name == null) {
      if(other.name != null)
      return false;
      }else if(!name.equals(other.name ))
      return false;
      return true;

      }
      }

      *****************************
      package heima.map;

      import java.util.HashMap;

      public class test {
      public static void main(String [] args) {
      HashMap<Student, String> hm = new HashMap<>();
      hm.put(new Student("张三", 23), "北京");
      hm.put(new Student("张三", 23), "上海");
      hm.put(new Student("李四", 24), "广州");
      hm.put(new Student("王五", 25), "深圳");
      System.out.println(hm);
      }
      }
      输出:


集合框架(LinkedHashMap的概述和使用)


  • A:案例演示
    • LinkedHashMap的特点
      • 底层是链表实现的可以保证怎么存就怎么取

        import java.util.LinkedHashMap;

        public class Demo_linkedhashmap {

        public static void main(String[] args) {
        LinkedHashMap<String, Integer> hm = new LinkedHashMap<>();
        hm.put("张三", 23);
        hm.put("李四", 24);
        hm.put("王五", 25);
        hm.put("赵六", 26);
        System.out.println(hm);

        }

        }
        输出:


集合框架(TreeMap集合键是Student值是String的案例)


  • A:案例演示
    • TreeMap集合键是Student值是String的案例

      package number1;

      public class Student implements Comparable {
      private String name;
      private int age;
      public Student() {}
      public Student(String name ,int age) {
      this.name = name ;
      this.age =age ;
      }
      public void setName (String name) {
      this.name = name;
      }
      public String getName(){
      return name;
      }
      public void setAge(int age) {
      this.age = age;
      }
      public int getAge() {
      return age;
      }
      @Override
      public String toString() {
      return "Student [name = "+ name +" , age = "+ age +"]";
      }
      @Override
      public int compareTo(Student o) {
      int num = this.age -o.age ;
      return num == 0 ? this.name.compareTo(o.name) : num;
      }

      }

      **************************************
      import number1.Student;
      import java.util.TreeMap;

      public class Demo_treemap {

      public static void main(String[] args) {
      TreeMap<Student,String> tm = new TreeMap<>();
      tm.put(new Student("张三", 23), "北京");
      tm.put(new Student("李四", 13), "上海");
      tm.put(new Student("王五", 33), "广州");
      tm.put(new Student("赵六", 43), "深圳");
      System.out.println(tm);
      }

      }
      输出:
      {Student [name = 李四 , age = 13]=上海, Student [name = 张三 , age = 23]=北京, Student [name = 王五 , age = 33]=广州, Student [name = 赵六 , age = 43]=深圳}
      ************************************************
      TreeMap<Student,String> tm = new TreeMap<>(new Comparator() {
      @Override
      public int compare(Stuednt s1, Student s2) {
      int num = s1.getName().compareTo(s2.getName()); //按照姓名比较,Unix码表值
      return num == 0 ? s1.getAge() - s2.getAge() : num;
      }
      });
      tm.put(new Student("张三", 23), "北京");
      tm.put(new Student("李四", 13), "上海");
      tm.put(new Student("王五", 33), "广州");
      tm.put(new Student("赵六", 43), "深圳");
      System.out.println(tm);
      输出:


集合框架(统计字符串中每个字符出现的次数)


  • A:案例演示
    • 需求:统计字符串中每个字符出现的次数

      String str = "aaaabbbcccccccccc";
      char[] arr = str.toCharArray(); //将字符串转换成字符数组
      HashMap<Character, Integer> hm = new HashMap<>(); //创建双列集合存储键和值

      for(char c : arr) { //遍历字符数组
      /if(!hm.containsKey(c)) { //如果不包含这个键
      hm.put(c, 1); //就将键和值为1添加
      }else { //如果包含这个键
      hm.put(c, hm.get(c) + 1); //就将键和值再加1添加进来
      }
      /

      hm.put(c, !hm.containsKey(c) ? 1 : hm.get(c) + 1);
      Integer i = !hm.containsKey(c) ? hm.put(c, 1) : hm.put(c, hm.get(c) + 1);
      }

      for (Character key : hm.keySet()) { //遍历双列集合
      System.out.println(key + "=" + hm.get(key));
      }
      输出:
      b = 3
      a = 4
      c = 10


集合框架(集合嵌套之HashMap嵌套HashMap)


  • A:案例演示
    • 集合嵌套之HashMap嵌套HashMap

      //Student必须重写equal方法和hashcode方法
      //定义第88期基础班
      HashMap<Student,String> hm88 = new HashMap<>();
      hm88.put(new Student("张三", 23), "北京");
      hm88.put(new Student("李四", 13), "上海");
      hm88.put(new Student("王五", 33), "广州");
      hm88.put(new Student("赵六", 43), "深圳");

      //定义第99期基础班
      HashMap<Student,String> hm99 = new HashMap<>();
      hm99.put(new Student("张", 223), "北京");
      hm99.put(new Student("李", 133), "上海");
      hm99.put(new Student("五", 335), "广州");
      hm99.put(new Student("六", 434), "深圳");

      //定义双元课堂
      HashMap<HashMap<Student,String>,String> hm = new HashMap<>();
      hm.put(hm88, "第88期基础班");
      hm.put(hm99, "第99期基础班");

      for(HashMap<Student, String> h : hm.keySet) { //hm.keyset()代表的是双列集合中键的集合
      String value = hm.get(h);
      for(Student key : h.keySet()) {
      String value2 = h.get(key);
      System.out.println(key + "=" + value2 + "=" + value);
      }

      }
      输出:
      Student [name = 六, age = 434] = 北京 = 第99期基础班


      。//注释:中间类似输出

      Student [name = 张三, age = 23] = 北京 = 第88期基础班

集合框架(HashMap和Hashtable的区别)(面试题)


  • A:面试题
    • HashMap和Hashtable的区别
      • 共同点:
        • 底层都是哈希算法,都是双列集合
      • 不同点:
        • Hashtable是JDK1.0版本出现的,是线程安全的,效率低,HashMap是JDK1.2版本出现的,是线程不安全的,效率高
        • Hashtable不可以存储null键和null值,HashMap可以存储null键和null值
  • B:案例演示
    • HashMap和Hashtable的区别

集合框架(Collections工具类的概述和常见方法讲解)


  • A:Collections类概述

    • 针对集合操作 的工具类
  • B:Collections成员方法

  • public static void sort(List list)
    public static int binarySearch(List list,T key) 二分查找法 public static T max(Collection coll)
    public static void reverse(List list) public static void shuffle(List list) 随机置换,可以洗牌

    import java.util.ArrayList;
    import java.util.Collections;

    public class collections {
    public static void main (String [] args) {
    ArrayList list = new ArrayList<>();
    list.add("s");
    list.add("a");
    list.add("d");
    list.add("z");
    list.add("c");
    System.out.println(list);
    Collections.sort(list);
    System.out.println(list);
    }

    }
    输出:
    [s, a, d, z, c]
    [a, c, d, s, z]
    ********************************************************
    import java.util.ArrayList;
    import java.util.Collections;

    public class collections {
    public static void main (String [] args) {
    ArrayList list = new ArrayList<>();
    list.add("a");
    list.add("a");
    list.add("d");
    list.add("f");
    list.add("z");
    System.out.println(list);
    System.out.println(Collections.binarySearch(list, "f"));
    }

    }
    输出:
    [a, a, d, f, z]
    3
    ********************************************************
    import java.util.Collections;

    public class collections {
    public static void main (String [] args) {
    ArrayList list = new ArrayList<>();
    list.add("a");
    list.add("a");
    list.add("d");
    list.add("f");
    list.add("z");
    System.out.println(list);
    System.out.println(Collections.max(list)); //根据默认排序结果,获取最大值
    }

    }
    输出:
    [a, a, d, f, z]
    z
    ********************************************************
    import java.util.ArrayList;
    import java.util.Collections;

    public class collections {
    public static void main (String [] args) {
    ArrayList list = new ArrayList<>();
    list.add("a");
    list.add("a");
    list.add("d");
    list.add("f");
    list.add("z");
    System.out.println(list);
    Collections.reverse(list);
    System.out.println(list);
    }
    输出:
    [a, a, d, f, z]
    [z, f, d, a, a]


集合框架(模拟斗地主洗牌和发牌)


  • A:案例演示
    • 模拟斗地主洗牌和发牌,牌没有排序

      //买一副扑克
      String[] num = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
      String[] color = {"方片","梅花","红桃","黑桃"};
      ArrayList poker = new ArrayList<>();

      for(String s1 : color) {
      for(String s2 : num) {
      poker.add(s1.concat(s2));
      }
      }

      poker.add("小王");
      poker.add("大王");
      //洗牌
      Collections.shuffle(poker);
      //发牌
      ArrayList gaojin = new ArrayList<>();
      ArrayList longwu = new ArrayList<>();
      ArrayList me = new ArrayList<>();
      ArrayList dipai = new ArrayList<>();

      for(int i = 0; i < poker.size(); i++) {
      if(i >= poker.size() - 3) {
      dipai.add(poker.get(i));
      }else if(i % 3 == 0) {
      gaojin.add(poker.get(i));
      }else if(i % 3 == 1) {
      longwu.add(poker.get(i));
      }else {
      me.add(poker.get(i));
      }
      }

      //看牌

      System.out.println(gaojin);
      System.out.println(longwu);
      System.out.println(me);
      System.out.println(dipai);

集合框架(模拟斗地主洗牌和发牌并对牌进行排序的代码实现)


  • A:案例演示

    • 模拟斗地主洗牌和发牌并对牌进行排序的代码实现
  • //买一副牌
    String[] num = {"3","4","5","6","7","8","9","10","J","Q","K","A","2"};
    String[] color = {"方片","梅花","红桃","黑桃"};
    HashMap<Integer, String> hm = new HashMap<>(); //存储索引和扑克牌
    ArrayList list = new ArrayList<>(); //存储索引
    int index = 0; //索引的开始值
    for(String s1 : num) {
    for(String s2 : color) {
    hm.put(index, s2.concat(s1)); //将索引和扑克牌添加到HashMap中
    list.add(index); //将索引添加到ArrayList集合中
    index++;
    }
    }
    hm.put(index, "小王");
    list.add(index);
    index++;
    hm.put(index, "大王");
    list.add(index);
    //洗牌
    Collections.shuffle(list);
    //发牌
    TreeSet gaojin = new TreeSet<>();
    TreeSet longwu = new TreeSet<>();
    TreeSet me = new TreeSet<>();
    TreeSet dipai = new TreeSet<>();

    for(int i = 0; i < list.size(); i++) {
    if(i >= list.size() - 3) {
    dipai.add(list.get(i)); //将list集合中的索引添加到TreeSet集合中会自动排序
    }else if(i % 3 == 0) {
    gaojin.add(list.get(i));
    }else if(i % 3 == 1) {
    longwu.add(list.get(i));
    }else {
    me.add(list.get(i));
    }
    }

    //看牌
    lookPoker("高进", gaojin, hm);
    lookPoker("龙五", longwu, hm);
    lookPoker("冯佳", me, hm);
    lookPoker("底牌", dipai, hm);

    }

    public static void lookPoker(String name,TreeSet ts,HashMap<Integer, String> hm) {
    System.out.print(name + "的牌是:");
    for (Integer index : ts) {
    System.out.print(hm.get(index) + " ");
    }

    System.out.println();
    }


posted @ 2021-03-28 00:37  言非  阅读(150)  评论(0)    收藏  举报