Java foundation (Map collection)

1. Overview of Map interface

       The Map interface is a two-column collection, and each element of it contains a key object (key) and a value object (value). There is a correspondence between the objects, called a map.

       When accessing an element, as long as the key is specified, the corresponding value can be found.

       For objects that map keys to values, a map cannot contain duplicate keys, and each key guides at most one value.

2. Overview of Map Common Collections

  1. HashMap <K, V> : Hash table structure used to store data, the access sequence of elements cannot be guaranteed to be consistent. Since the key must be unique and not duplicated, the hashCode () method and equals () method of the key need to be rewritten.
  2. LinkedHashMap <K, V> : There is a subclass LinkedHashMap under HashMap, which stores the hash table structure + linked list structure used by the stored data. The linked list structure can ensure that the access sequence of elements is consistent; the hash table structure can ensure that the keys are unique and not duplicated, and the hashCode () method and equals () method of the key need to be rewritten.
  3. TreeMap <K, V> : The binary tree principle guarantees that the keys are unique, and the keys can be sorted in the specified order.

Third, the commonly used methods in the Map interface

Examples:

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

public class demo_map常用方法 {
    public static void main(String[] args) {
        //Map<K,V> K:键  V:值
        Map<String,String> map=new HashMap<>();
        //存入值,返回之前的值,如果没有,返回null
        map.put("111","aaa");
        map.put("222","bbb");
        System.out.println(map);
        //获取值 根据键获取值,不存在返回null
        String value=map.get("111");
        System.out.println(value);
        //删除指定key的值
        map.remove("111");
        System.out.println(map);
    }
}

operation result:

Fourth, the traversal of the Map collection

Two traversal methods

Examples:

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

public class demo_集合遍历 {
    public static void main(String[] args) {
        Map<String,String> map=new HashMap<>();
        map.put("1","aaa");
        map.put("2","bbb");
        map.put("3","ccc");
        map.put("4","ddd");
        map.put("5","eee");
        //第一种遍历方式
        //1.先获取所有的键
        Set<String> key=map.keySet();
        //2.遍历键的集合
        for(String k:key){
            String value=map.get(k);
            System.out.println("获取到的键和值:"+k+" "+value);
        }
        System.out.println("-----------------");
        //第二种遍历方式map.entrySet()ctrl+alt+v
        //1.获取所有键值对
        Set<Map.Entry<String, String>> entries = map.entrySet();
        //2.遍历set集合,获取键值对象
        for(Map.Entry<String,String>entry:entries){
            String key1=entry.getKey();
            String value1=entry.getValue();
            System.out.println("获取到的键和值:"+key1+" "+value1);
        }
    }
}

operation result:

Five, HashMap store custom type key value

When storing a custom object in HashMap, if the custom object exists as a key, to ensure that the object is unique at this time, you must override the hashCode and equals methods of the object

Examples:

import java.util.HashMap;

public class HashMap_存储自定义对象 {
    public static void main(String[] args) {
        HashMap<Student,String> hashMap=new HashMap<>();
        hashMap.put(new Student("yyy",18),"111");
        hashMap.put(new Student("wtc",18),"222");
        hashMap.put(new Student("yyy",18),"333");
        System.out.println(hashMap);
    }
}
class Student{
    String name;
    int age;

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

    @Override
    public boolean equals(Object o) {
        return super.equals(o);
    }

    @Override
    public int hashCode() {
        return this.name.hashCode()+age;
    }

    @Override
    public String toString() {
        return "姓名:" + name  +
                " 年龄:" + age;
    }
}

operation result:

Six, the use of TreeMap

The binary tree principle guarantees that the keys are unique, and the keys can be sorted in the specified order.

Examples:

import java.util.Comparator;
import java.util.TreeMap;

public class demo_treemap {
    public static void main(String[] args) {
        //TreeMap键是有序的
        TreeMap<String,String> treeMap=new TreeMap<>();
        treeMap.put("02","aaa");
        treeMap.put("01","aaa");
        treeMap.put("04","aaa");
        treeMap.put("03","aaa");
        System.out.println(treeMap);
        /**
         * 自定义对象作为TreeMap的key
         */
        TreeMap<Teacher,String> treeMap1=new TreeMap<>(new Comparator<Teacher>() {
            @Override
            public int compare(Teacher o1, Teacher o2) {
                //按年龄排序
                return o1.age-o2.age;
            }
        });
        treeMap1.put(new Teacher("yyy",19),"aaa");
        treeMap1.put(new Teacher("wtc",18),"bbb");
        treeMap1.put(new Teacher("yw",20),"ccc");
        System.out.println(treeMap1);
    }
}
class Teacher {
    String name;
    int age;

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

    @Override
    public String toString() {
        return "Teacher{" +
                "姓名:" + name+
                '}';
    }
}

operation result:

7. Exercises

    1. TreeMap counts the occurrence of strings

Examples:

import java.util.TreeMap;
import java.util.Set;
public class demo_TreeMap统计字符串出现次数 {
    public static void main(String[] args) {
        String s="zzzszsdxxaasswwwayy";
        TreeMap<Character,Integer> treeMap=new TreeMap<>();
        for(int i=0;i<s.length();i++){
            char c=s.charAt(i);
            Integer value=treeMap.get(c);
            if(value!=null){
                //之前存过值
                value++;
                treeMap.put(c,value);
            }
            else{
                //之前没存过
                treeMap.put(c,1);
            }
        }
        StringBuffer ss=new StringBuffer();
        Set<Character> keyset=treeMap.keySet();
        for(Character key:keyset){
            ss.append(key).append("(").append(treeMap.get(key)).append(")   ");
        }
        System.out.println(ss.toString());
    }
}

operation result:

        2. HashMap collection nested HashMap collection case

Examples:

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

public class demo_模拟存储班级信息 {
    public static void main(String[] args) {
        HashMap<String,String> hashMap1=new HashMap<>();
        hashMap1.put("001","小米");
        hashMap1.put("002","糖糖");
        hashMap1.put("002","妮妮");
        HashMap<String,String> hashMap2=new HashMap<>();
        hashMap2.put("001","天天");
        hashMap2.put("002","乐乐");
        hashMap2.put("002","可可");
        HashMap<String,HashMap<String,String>> hashMap=new HashMap<>();
        hashMap.put("2017",hashMap1);
        hashMap.put("2018",hashMap2);
        //第一种键找值
        Set<String> keyset=hashMap.keySet();
        for(String key:keyset){
            HashMap<String,String> ch=hashMap.get(key);
            Set<String> chkeyset=ch.keySet();
            System.out.println(key);
            for(String chk:chkeyset){
                System.out.println("学号:"+chk+" 姓名:"+ch.get(chk));
            }
        }
        System.out.println("---------------------------");
        //第二种获取键值对
        Set<Map.Entry<String,HashMap<String,String>>> entrySet=hashMap.entrySet();
        for(Map.Entry<String,HashMap<String,String>> entry:entrySet){
            String key=entry.getKey();
            HashMap<String,String> childHashmap=entry.getValue();
            System.out.println(key);
            for(Map.Entry<String,String> chEntry:childHashmap.entrySet()){
                String s1=chEntry.getKey();
                String s2=chEntry.getValue();
                System.out.println("学号:"+s1+" 姓名:"+s2);
            }
        }

    }
}

operation result:

    3. ArrayList collection nested HashMap collection

Examples:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;
import java.util.Map;

public class demo_Arraylist嵌套map {
    public static void main(String[] args) {
        HashMap<String,String> hashMap1=new HashMap<>();hashMap1.put("001","小米");
        hashMap1.put("002","糖糖");
        hashMap1.put("002","妮妮");
        HashMap<String,String> hashMap2=new HashMap<>();
        hashMap2.put("001","天天");
        hashMap2.put("002","乐乐");
        hashMap2.put("002","可可");
        ArrayList<HashMap<String,String>> list=new ArrayList<>();
        list.add(hashMap1);
        list.add(hashMap2);
        //第一种方式
        for(int i=0;i<list.size();i++){
            HashMap<String,String> hashMap=list.get(i);
            Set<Map.Entry<String,String>> entrySet=hashMap.entrySet();
            for(Map.Entry<String,String> entry:entrySet){
                System.out.println("学号:"+entry.getKey()+"姓名:"+entry.getValue());
            }
        }
        System.out.println("-----------------");
        //第二种方式
        for(HashMap<String,String> hashMap:list){
            Set<Map.Entry<String,String>> entrySet=hashMap.entrySet();
            for(Map.Entry<String,String> entry:entrySet){
                System.out.println("学号:"+entry.getKey()+" 姓名:"+entry.getValue());
            }
        }
    }
}

operation result:

Published 75 original articles · praised 164 · 110,000 views

Guess you like

Origin blog.csdn.net/qq_41679818/article/details/96868449