Programmer's essential knowledge: the common method of using Map

Insert picture description here

1. Map description

 Map没有像List、Queue、Set一样继承Collection,它是独立于它们存在的。
Map是一个接口类,实现的类有HashMap和TreeMap。
Map在现实生活中对什么进行抽象的呢?--------姓名--个人资料,就是key-value,
但还是以key为准。

Insert picture description here

2. Description of common methods of Map

1. Description of Map.Entry<k,v>

1. Regarding Map.Entry<k,v>, it is actually an internal class implemented in Map to store the <key, value> key-value pair mapping relationship , so the Map.Entry method is used when calling;
2 .The inner class also provides the acquisition of <key, value>, the setting of value and the comparison method of key: the three methods in the box are more important. Insert picture description here
Note : There is no setting of Key in Map.Entry<K,V> Method ---------------- That is because when HashMap is sorted and compared, it is like a search binary tree, its key is the only constant, and the change of the key will affect the tree Structure , so the key cannot be changed.

2. Common methods

method Explanation
V get(Object key) Return the value corresponding to the key
V getOrDefault(Object key,V defaultValue) Return the value corresponding to the key. If the key does not exist, return to the default setting (only available after jdk1.8)
V put(K key,V value) Set the value corresponding to the key
V remove(Object key) Delete the mapping relationship corresponding to the key
Set keySet() Return a unique collection of all keys
Collection values() Return a repeatable collection of all values
Set<Map.Entry<K,V>> entrySet() Return all key-value mapping relationships
boolean containsKey Return whether key is included
boolean containsValue(Object value) Determine whether to include value

3. The difference between TreeMap and HashMap

TreeMap HashMap
The underlying structure is a red-black tree The underlying structure is a hash bucket
Insert/delete/search time complexity O(log(n)) O (1)
About key order Disorder
Thread unsafe Thread unsafe
When inserting/deleting/searching: comparison of elements is required Calculate the hash address through the hash function
Application Scenario: Under the scenario that requires ley orderly It does not care whether the key is in order, but requires higher time performance

4. Pay attention to some small concepts

(1) Map is an interface and cannot directly instantiate an object . If you want to instantiate an object , you can only instantiate its implementation class TreeMap or HashMap;
(2) The key that stores the key-value pair in the Map is unique, and the value can be repeated ;
(3) When inserting a key-value pair in the Map, the key cannot be empty, otherwise a NullPointerException will be thrown , but the value can be empty;
(4) The key in the Map can be completely separated and stored in the Set for access (Because the key cannot be repeated);
(5) The value in the Map can be completely separated and stored in any subset of the Collection (the value may be repeated);
(6) The key in the key-value pair of the Map cannot be modified directly, but the value can be Modify, if you want to modify the key, you can only delete the key first, and then re-insert it.

5. Code

The main thing is to call some methods of Map, specifically how to call and some issues to pay attention to have been supplemented: the code is as follows

import java.util.Map;
import java.util.TreeMap;

public class Map1 {
    
    
    public static void main(String[] args) {
    
    
        
        Map<String,String> m=new TreeMap<>();
        
        //put(key,value):插入key-value的键值对
        m.put("林冲","豹子头");
        m.put("鲁智深","花和尚");
        m.put("武松","行者");
        m.put("宋江","及时雨");
        
        
        String str=m.put("李逵","黑旋风");
        System.out.println(m.size());
        System.out.println(m);

        //put(key,value):注意key不能为空,但是value可以为空,key如果为空,会抛空指针异常
        str=m.put("无名",null);
        System.out.println(m.size());

        //如果key存在,put(key,value)则会替换掉原来的value,返回旧的value
        str=m.put("李逵","铁牛");

        //get(key),返回key所对应的value
        //如果key存在,则返回key对应的value,如果key不存在,则返回null
        System.out.println(m.get("鲁智深"));
        System.out.println(m.get("史进"));

        //containKey(key):检查key是否包含在Map中,时间复杂度O(log(n))
        //按照红黑树的主性质进行查找
        //找到返回true,找不到,则返回false
        System.out.println(m.containsKey("林冲"));
        System.out.println(m.containsKey("史进"));

        //containValue(value):检测value是否包含在Map中,时间复杂度O(n)
        //因为TreeMap是按照key进行组织的,因此查找value时候就需要整体遍历
        //找到返回true,找不到返回false
        System.out.println(m.containsValue("豹子头"));
        System.out.println(m.containsValue("九纹龙"));

        //打印所有的key
        for(String s:m.keySet()){
    
    
            System.out.println(s+" ");
        }
        System.out.println();

        //打印所有的value
        for(String s:m.values()){
    
    
            System.out.println(s+" ");
        }
        System.out.println();

        //打印所有的键值对
        //entrySet():将Map中的键值对放在Set中返回了
        for(Map.Entry<String,String> entry:m.entrySet()){
    
    
            System.out.println(entry.getKey()+"---->"+entry.getValue());
        }
        System.out.println();

Three, summary

1. Understand the concept of Map, know that you can use Map to access the mapping between objects. When doing questions, for example: find the most frequent words, <number, word>, you can use TreeMap to solve, everything is relevant You can use Map if there is a one-to-one relationship between two attributes;
2. To be familiar with some common methods of Map, it will be more convenient to do the questions.

Guess you like

Origin blog.csdn.net/m0_46551861/article/details/109405713