Java从入门到放弃18---Map集合/HashMap/LinkedHashMap/TreeMap/集合嵌套/Collections工具类常用方法

Java从入门到放弃18—Map集合/HashMap/LinkedHashMap/TreeMap/集合嵌套/Collections工具类常用方法

01 Map集合

  • Map集合处理键值映射关系的数据
为了方便处理键值映射关系的数据,Java提供了一种Map集合
键值映射关系的数据(一个键对应一个值,如一个学号对应一个学生)
在双列集合中,所有的数据结构只和key有关,和value无关。键相同时,会覆盖value。
基于哈希表的 Map 接口的实现。此实现提供所有可选的映射操作,并允许使用 null 值和 null 键。
  • Map接口和Collection接口的区别
Map接口和Collection接口的不同
	Map是双列的,Collection是单列的
	Map的键唯一,Collection的子体系Set是唯一的
	Map集合的数据结构针对键有效,跟值无关;Collection集合的数据结构是针对元素有效
  • Map的常用方法
通过put(key,value);方法添加元素
通过clear();清楚集合
通过get(key);根据键获取值
通过remove(key);根据键移除这一组键值映射关系的数据
通过keySet();获取所有键的set集合
通过values();获取所有值的collection集合
通过entrySet();返回一个键值对的set集合
通过containsKey(key);判断集合中有没有键key
通过containsValue(values);判断集合中有没有值values
通过isEmpty();判断集合是否为空
通过size();获取集合中的键值对的对数
  • Map的遍历
//方式1:键找值
public class Test{
    public static void main(String[] args){
        HashMap hashMap=new HashMap<>();
        hashMap.put(1,"a");
        hashMap.put(2,"b");
        hashMap.put(3,"c");
        Set keys=hashMap.keySet();
        for(Integer i :keys){
            System.out.println(i+"|"+hashMap.get(i));
        }
    }
}
//方式2:通过entrySet();获取键值对象Entry,用set集合接收;再遍历Entry。Entry提供了getKey()和getValve方法分别获取键值。Entry重写了toString方法,打印的是对象的内容而不是地址值。
public class Test{
    public static void main(String[] args){
        HashMap hashMap=new HashMap<>();
        hashMap.put(1,"a");
        hashMap.put(2,"b");
        hashMap.put(3,"c");
        Set> entries = hashMap.entrySet();
        for (Map.Entry entry : entries) {
            //System.out.println(entry);
            Integer key = entry.getKey();
            String value = entry.getValue();
            System.out.println(key+"==="+value);
        }
    }
}

02 HashMap

  • HashMap 底层键的数据结构是哈希表,是元素为链表的数组,具有链表和数组的特点。键唯一且无序。HashMap允许使用 null 值和 null 键。
  • HashMap在JDK1.8之前采用的是数组加链表的形式实现其数据结构。
    JDK1.8之后采用数组加链表加红黑树实现。当链表长度超过阈值8之后,不再采用链表结构进行存储,转而采用红黑树结构。红黑树的引入是为了优化查询效率。
public class MyTest {
    public static void main(String[] args) {
        HashMap hashMap = new HashMap<>();
        hashMap.put(1, "aaa");
        hashMap.put(1, "bbb");
        hashMap.put(2, "ccc");
        hashMap.put(3, "ddd");
        hashMap.put(4, "eee");
        hashMap.put(5, "fff");
        hashMap.put(null,null);
        System.out.println(hashMap.get(null));
        //获取所有键的集合
        Set integers = hashMap.keySet();
        System.out.println(integers);
        //获取所有值的集合
        Collection values = hashMap.values();
        System.out.println(values);
        //判断集合有没有1这个键
        boolean b = hashMap.containsKey(1);
        //判断集合中有么有bbb这个值
        boolean flag = hashMap.containsValue("bbb");
        //获取集合的长度
        System.out.println(hashMap.size());
    }
}


03 LinkedHashMap

  • LinkedHashMap 底层键的数据结构是链表和哈希表,键表保证键有序,哈希表保证键唯一。
LinkedHashMap linkedHashMap=new LinkedHashMap<>();
linkedHashMap.put(key,value);
public class MyTest2 {
    public static void main(String[] args) {

        //键的数据结构是链表和哈希表,链表保证键有序,哈希表保证键唯一
        LinkedHashMap linkedHashMap = new LinkedHashMap<>();
        linkedHashMap.put("a", "1");
        linkedHashMap.put("a", "2");
        linkedHashMap.put("b", "2");
        linkedHashMap.put("c", "3");
        linkedHashMap.put("d", "4");
        Set strings = linkedHashMap.keySet();
        for (String key : strings) {
            System.out.println(key + "|" + linkedHashMap.get(key));
        }
    }
}
//运行结果:a|2
          b|2
          c|3
          d|4

04 TreeMap

  • TreeMap 键的数据结构是红黑树结构。键可以排序且唯一。TreeMap 键不允许插入null。
  • 排序分为自然排序和比较器排序 ,线程是不安全的,但效率比较高
  • 自然排序(空参构造)
//student类
public class Student implements Comparable{//元素要实现Comparable接口并重写compareTo方法
    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;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return age == student.age &&
                Objects.equals(name, student.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }

    @Override
    public int compareTo(Student o) {//按年龄排序
        int num=this.age-o.age;
        int num2=num==0?this.name.compareTo(o.name):num;


        return num2;
    }
}
//测试类
public class MyTest {
    public static void main(String[] args) {
        TreeMap treeMap = new TreeMap<>();
        treeMap.put(new Student("Snow", 23), "1");
        treeMap.put(new Student("John", 23), "2");
        treeMap.put(new Student("Alice", 21), "3");
        treeMap.put(new Student("Bob", 24), "4");
        treeMap.put(new Student("Lily", 26), "5");
        treeMap.put(new Student("Rose", 25), "6");
        treeMap.put(new Student("Jack", 28), "7");
        Set> entries = treeMap.entrySet();
        for (Map.Entry entry : entries) {
            Student key = entry.getKey();
            String value = entry.getValue();
            System.out.println(key+"==="+value);
        }

    }
}
  • 比较器排序
//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;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return age == student.age &&
                Objects.equals(name, student.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }


}

//测试类
public class MyTest2 {
    public static void main(String[] args) {
        TreeMap treeMap = new TreeMap<>(new Comparator() {
            @Override
            public int compare(Student s1, Student s2) {
                int num = s1.getAge()-s2.getAge();
                int num2 = num == 0 ? s1.getName().compareTo(s2.getName()) : num;
                return -num2;//年龄从大到小排序
            }
        });
        treeMap.put(new Student("Snow", 23), "1");
        treeMap.put(new Student("John", 23), "2");
        treeMap.put(new Student("Alice", 21), "3");
        treeMap.put(new Student("Bob", 24), "4");
        treeMap.put(new Student("Lily", 26), "5");
        treeMap.put(new Student("Rose", 25), "6");
        treeMap.put(new Student("Jack", 28), "7");
    }
}

05 案例:统计字符串中每个字符出现的次数

public class MyTest {
    public static void main(String[] args) {
        HashMap hashMap = new HashMap<>();
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一段字符串");
        String str = sc.nextLine();
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            if (!hashMap.containsKey(ch)) {
                hashMap.put(ch, 1);
            } else {
                //取出旧值
                Integer integer = hashMap.get(ch);
                integer++;
                hashMap.put(ch, integer);//键相同值覆盖
            }
        }
        StringBuilder sb = new StringBuilder();
        Set> entries = hashMap.entrySet();
        for (Map.Entry entry : entries) {
            sb.append(entry.getKey()).append("(").append(entry.getValue()).append(")");
        }
        String s = sb.toString();
        System.out.println(s);
    }
}

06 集合嵌套

  • HashMap嵌套HashMap
HashMap hashMap01 = new HashMap<>();
HashMap> hashMap02 = new HashMap<>();
  • HashMap嵌套ArrayList
ArrayList<> list = new ArrayList<>();
HashMap> hashMap = new HashMap<>();
  • ArrayList嵌套HashMap
HashMap hashMap01 = new HashMap<>();
ArrayList> list = new ArrayList<>();

07 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):					随机置换

你可能感兴趣的:(Java基础)