JAVASE基础模块二十六(Map集合 HashMap LinkedHashMap Hashtable TreeMap)

JAVASE基础模块二十六(Map集合 HashMap LinkedHashMap Hashtable TreeMap)

MaP集合

  • 在生活中 有一种数据比较常见 比如一个 学号—学生

    1. “s001”----------“张三”
    2. “s002”----------“张四”
    3. “s003”----------“张五”
    import java.util.ArrayList;
    import java.util.Arrays;
    public class Test {
        public static void main(String[] args) {
            ArrayList<String> d = new ArrayList<>();
            d.add("s001----------张三");
            d.add("s002----------张四");
            d.add("s003----------张五");
            System.out.println(Arrays.toString(d.get(0).split("-+")));        System.out.println(Arrays.toString(d.get(0).split("-+")));       System.out.println(Arrays.toString(d.get(0).split("-+")));
            }
    }
    运行结果:
    [s001, 张三]
    [s001, 张三]
    [s001, 张三]
    
    Process finished with exit code 0
    
  • JAVA对于这种键值映射到值的数据对象 为了方便我们操作 提供了Map集合

  • Map之所以被称为双列集合 是由于它有键 有值

  • Map分类

    1. HashMap
    2. HashTable
    3. LinkedHashMap
    4. TreeMap
  • 特点:所有双列集合的数据结构 只跟键有关 跟值没关系

    1. Map:双列集合 一个键只能映射一个值 键相同 值就会被覆盖
    2. HashMap:键的数据结构是哈希表 键无序且唯一 并且允许使用null值和null键 线程不安全 效率高
    3. Hashtable:不允许null值和null键 线程安全 效率低
    4. LinkedHashMap:键的数据结构是链表和哈希表 键有序且唯一 链表保证有序 哈希表保证唯一
    5. TreeMap

    HashMap

    1. 添加元素 d.put(“莱茵科技”, “uu”);
    2. 当键相同 值覆盖 返回的是上一次这个键所映射的旧值
    3. 当键名为英文时键值顺序为有序
    4. 当键名为中文时键值顺序为无序
    import java.util.HashMap;
    
    public class HashM {
        public static void main(String[] args) {
            HashMap<String, String> d = new HashMap<>();
            String f=d.put("莱茵科技", "uu");//添加元素
            //当键相同 值覆盖 返回的是上一次这个键所映射的旧值
            String f1=d.put("莱茵科技", "22");
            d.put("博士", "tt");
            d.put("阿米娅", "ee");
            d.put("银灰", "ww");
            System.out.println(d);//顺序为无序
            System.out.println(f);
            System.out.println(f1);
        }
    }
    运行结果:
    {阿米娅=ee, 银灰=ww, 莱茵科技=22, 博士=tt}
    null
    uu
    
    Process finished with exit code 0
    
    1. 方法

      • 清空
      import java.util.HashMap;
      
      public class ShanChu {
          public static void main(String[] args) {
              HashMap<String, String> d = new HashMap<>();
              d.put("莱茵科技", "22");
              d.put("博士", "tt");
              d.put("阿米娅", "ee");
              d.put("银灰", "ww");
              //清空集合
              d.clear();
              //集合长度
              System.out.println(d.size());
          }
      }
      运行结果:
      0
      Process finished with exit code 0
      
      • 其他方法
      import java.util.HashMap;
      
      public class Sc {
          public static void main(String[] args) {
              HashMap<String, String> d = new HashMap<>();
              d.put("莱茵科技", "22");
              d.put("博士", "tt");
              d.put("阿米娅", "ee");
              d.put("银灰", "ww");
              //集合长度
              System.out.println(d.size());
              //返回的是键对应的值
              String dd = d.remove("博士");
              System.out.println(dd);
              System.out.println(d);
              //键是否存在
              System.out.println(d.containsKey("博士"));
              System.out.println(d.containsKey("银灰"));
              //通过键来获取值
              System.out.println(d.get("阿米娅"));
              System.out.println(d.get("崖心"));
              //通过键来获取值 找不到返回备用
               System.out.println(d.getOrDefault("崖心心", "发发"));
              //判断集合是否为空
              System.out.println(d.isEmpty());
          }
      }
      运行结果:
      4
      tt
      {阿米娅=ee, 银灰=ww, 莱茵科技=22}
      false
      true
      ee
      null
      发发
      false
      
      Process finished with exit code 0
      
  • 双列集合的遍历

    1. 键找值 遍历HashMap
    import java.util.HashMap;
    import java.util.Set;
    
    public class Bl1 {
        public static void main(String[] args) {
            HashMap<String, String> d = new HashMap<>();
            d.put("莱茵科技", "22");
            d.put("博士", "tt");
            d.put("阿米娅", "ee");
            d.put("银灰", "ww");
            Set<String> dd = d.keySet();
            for (String s : dd) {
                System.out.println(s+"\t"+d.get(s));
            }
        }
    }
    运行结果:
    阿米娅	ee
    银灰	ww
    莱茵科技	22
    博士	tt
    
    Process finished with exit code 0
    
    1. entrySet() 遍历HashMap
    package com.westos.X2;
    
    import java.util.HashMap;
    import java.util.Map;
    import java.util.Set;
    
    public class Bl2 {
        public static void main(String[] args) {
            HashMap<String, String> d = new HashMap<>();
            d.put("莱茵科技", "22");
            d.put("博士", "tt");
            d.put("阿米娅", "ee");
            d.put("银灰", "ww");
            Set<Map.Entry<String, String>> ff = d.entrySet();
            for (Map.Entry<String, String> ee : ff) {
            System.out.println(ee);
              
            }
        }
    }
    运行结果:
    阿米娅=ee
    银灰=ww
    莱茵科技=22
    博士=tt
    
    Process finished with exit code 0
    
    1. values() 值得获取
    import java.util.Collection;
    import java.util.HashMap;
    
    public class Zhi {
        public static void main(String[] args) {
            HashMap<String, String> d = new HashMap<>();
            d.put("莱茵科技", "22");
            d.put("博士", "tt");
            d.put("阿米娅", "ee");
            d.put("银灰", "ww");
            Collection<String> dd = d.values();
            for (String s : dd) {
                System.out.println(s);
            }
    
        }
    }
    运行结果:
    ee
    ww
    22
    tt
    
    Process finished with exit code 0
    
  • 键名相同与不同问题

    1. 键名为string 值为student
    import java.util.HashMap;
    import java.util.Map;
    import java.util.Set;
    
    public class Stu {
        public static void main(String[] args) {
            HashMap<String, Student> d = new HashMap<>();
            d.put("莱茵科技", new Student("22"));
            d.put("博士", new Student("33"));
            d.put("阿米娅", new Student("44"));
            d.put("阿米娅", new Student("49"));
            d.put("银灰", new Student("55"));
            d.put("银灰", new Student("66"));
            Set<Map.Entry<String, Student>> ff = d.entrySet();
            for (Map.Entry<String, Student> ee : ff) {
                System.out.println(ee);
            }
    
        }
    }
    
    class Student {
        private String name;
    
        public Student(String name) {
            this.name = name;
        }
    
        @Override
        public String toString() {
            return "Student{" +
                    "name='" + name + '\'' +
                    '}';
        }
    }
    运行结果:
    阿米娅=Student{name='49'}
    银灰=Student{name='66'}
    莱茵科技=Student{name='22'}
    博士=Student{name='33'}
    
    Process finished with exit code 0
    
    1. 键名为stud 值为string

      • 比较地址值而不是名字
      import java.util.HashMap;
      import java.util.Map;
      import java.util.Objects;
      import java.util.Set;
      public class Mxt {
          public static void main(String[] args) {
              HashMap<Stud,String> d = new HashMap<>();
              d.put(new Stud("弎屲"),"莱茵科技" );
              d.put( new Stud("弎屲"),"博士");
              d.put( new Stud("弎屲"),"阿米娅");
              d.put(new Stud("信息"),"阿米娅");
              d.put( new Stud("大大"),"银灰");
              d.put(new Stud("方方"),"银灰");
              Set<Map.Entry<Stud,String>> ff = d.entrySet();
              for (Map.Entry<Stud,String> ee : ff) {
                  System.out.println(ee);
              }
      
          }
      }
      class Stud{
          private String name;
      
          public Stud(String name) {
              this.name = name;
          }
          @Override
          public String toString() {
              return "Student{" +
                      "name='" + name + '\'' +
                      '}';
          }
      }
      运行结果:
      Student{name='弎屲'}=莱茵科技
      Student{name='大大'}=银灰
      Student{name='弎屲'}=阿米娅
      Student{name='弎屲'}=博士
      Student{name='信息'}=阿米娅
      Student{name='方方'}=银灰
      
      Process finished with exit code 0
      
      • 原因 HashMap重写了hashCode()与equals()方法
      import java.util.HashMap;
      import java.util.Map;
      import java.util.Objects;
      import java.util.Set;
      public class Mxt {
          public static void main(String[] args) {
              HashMap<Stud,String> d = new HashMap<>();
              d.put(new Stud("弎屲"),"莱茵科技" );
              d.put( new Stud("弎屲"),"博士");
              d.put( new Stud("弎屲"),"阿米娅");
              d.put(new Stud("信息"),"阿米娅");
              d.put( new Stud("大大"),"银灰");
              d.put(new Stud("方方"),"银灰");
              Set<Map.Entry<Stud,String>> ff = d.entrySet();
              for (Map.Entry<Stud,String> ee : ff) {
                  System.out.println(ee);
              }
      
          }
      }
      class Stud{
          private String name;
      
          public Stud(String name) {
              this.name = name;
          }
      
          @Override
          public boolean equals(Object o) {
              if (this == o) return true;
              if (o == null || getClass() != o.getClass()) return false;
              Stud stud = (Stud) o;
              return Objects.equals(name, stud.name);
          }
      
          @Override
          public int hashCode() {
              return Objects.hash(name);
          }
      
          @Override
          public String toString() {
              return "Student{" +
                      "name='" + name + '\'' +
                      '}';
          }
      }
      运行结果:
      Student{name='方方'}=银灰
      Student{name='大大'}=银灰
      Student{name='信息'}=阿米娅
      Student{name='弎屲'}=阿米娅
      
      Process finished with exit code 0
      

Hashtable

  • 区别

    1. HashMap键的数据结构是哈希表 键无序且唯一 并且允许使用null值和null键 线程不安全 效率高
    2. Hashtable不允许null值和null键 线程安全 效率低
    import java.util.HashMap;
    import java.util.Hashtable;
    
    public class HashT {
        public static void main(String[] args) {
            HashMap<String, String> d = new HashMap<>();
            d.put(null,null);
            Hashtable<String, String> dd = new Hashtable<>();
            dd.put(null,"hh");
            dd.put("nu",null);
            dd.put(null,null);
    
        }
    }
    运行结果:报错
    Exception in thread "main" java.lang.NullPointerException
    

LinkedHashMap

  • 特点:键的数据结构是链表和哈希表 键有序且唯一 链表保证有序 哈希表保证唯一

    import java.util.LinkedHashMap;
    
    public class LinkedH {
        public static void main(String[] args) {
            LinkedHashMap<String, String> d = new LinkedHashMap<>();
            d.put("莱茵科技", "22");
            d.put("博士", "tt");
            d.put("阿米娅", "ee");
            d.put("银灰", "ww");
            d.put("莱茵", "22");
            d.put("博", "tt");
            d.put("米娅", "ee");
            d.put("灰", "ww");
            System.out.println(d);
        }
    }
    运行结果:
    {莱茵科技=22, 博士=tt, 阿米娅=ee, 银灰=ww, 莱茵=22, 博=tt, 米娅=ee, 灰=ww}
    
    Process finished with exit code 0
    

TreeMap

  • 当键名为数值时会进行大小排序
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class TreeM {
    public static void main(String[] args) {
        TreeMap<Integer, String> d = new TreeMap<>();
        d.put(10,"莱茵科技");
        d.put(55,"博士");
        d.put(99,"阿米娅");
        d.put(46,"银灰");
        d.put(13,"莱茵");
        d.put(2,"博");
        d.put(66,"米娅");
        d.put(77,"灰");
        Set<Map.Entry<Integer,String>> ff = d.entrySet();
        for (Map.Entry<Integer,String> ee : ff) {
            System.out.println(ee);
        }
    }
}
运行结果:
2=博
10=莱茵科技
13=莱茵
46=银灰
55=博士
66=米娅
77=灰
99=阿米娅

Process finished with exit code 0
  • 当键名为字符串时会按照字典索引排序
import java.util.LinkedHashMap;
import java.util.TreeMap;

public class Jian {
    public static void main(String[] args) {
        TreeMap<String, String> d = new TreeMap<>();
        d.put("dft","莱茵科技");
        d.put("ert","博士" );
        d.put("asd","阿米娅 ");
        d.put("hui","银灰");
        d.put("iuy","莱茵" );
        d.put("bgt","博");
        d.put("gry","米娅" );
        d.put("fer","灰");
        System.out.println(d);
    }
}

运行结果:
{asd=阿米娅 , bgt=博, dft=莱茵科技, ert=博士, fer=灰, gry=米娅, hui=银灰, iuy=莱茵}

Process finished with exit code 0
  • 当键名为自定义类型时 要传入比较器进行比较
package com.westos.X2;

import java.util.*;

public class ZiDingYi {
    public static void main(String[] args) {
        TreeMap<Stude, String> d = new TreeMap<>(new Comparator<Stude>() {
            @Override
            public int compare(Stude o1, Stude o2) {
                int num = o1.getAge() - o2.getAge();
                int num2 = num == 0 ? o1.getName().compareTo(o2.getName()) : num;
                return num2;
            }
        });
        d.put(new Stude("弎屲", 98), "莱茵科技");
        d.put(new Stude("弎屲", 56), "博士");
        d.put(new Stude("弎屲", 23), "阿米娅");
        d.put(new Stude("信息", 111), "阿米娅");
        d.put(new Stude("大大", 85), "银灰");
        d.put(new Stude("方方", 22), "银灰");
        Set<Map.Entry<Stude, String>> ff = d.entrySet();
        for (Map.Entry<Stude, String> ee : ff) {
            System.out.println(ee);
        }
    }
}

class Stude {
    private String name;
    private int age;

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

    public int getAge() {
        return age;
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "Stude{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
运行结果:
Stude{name='方方', age=22}=银灰
Stude{name='弎屲', age=23}=阿米娅
Stude{name='弎屲', age=56}=博士
Stude{name='大大', age=85}=银灰
Stude{name='弎屲', age=98}=莱茵科技
Stude{name='信息', age=111}=阿米娅

Process finished with exit code 0
  • 利用Map统计字符个数
import java.util.Scanner;
import java.util.TreeMap;
public class LianXi {
    public static void main(String[] args) {
        TreeMap< Character,Integer> dd = new TreeMap<>();
        Scanner d = new Scanner(System.in);
        System.out.println("请输入字符串");
        String s=d.nextLine();
        for (int i = 0; i < s.length(); i++) {
            if(!dd.containsKey(s.charAt(i))){
                dd.put(s.charAt(i),1);
            }else{
                int m=dd.get(s.charAt(i));
                m++;
                dd.put(s.charAt(i),m);
            }
        }
    }
}
运行结果:
请输入字符串
hfuseirallgarurahaflhaeuaefhlvjkdslv
{a=6, d=1, e=3, f=3, g=1, h=4, i=1, j=1, k=1, l=5, r=3, s=2, u=3, v=2}

Process finished with exit code 0

待续…

©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页