HashMap realizes the method of hanging multiple values under a key

In the standard Java Map interface, a key (key) can only be mapped to a value (value). This means that in an ordinary Map implementation (such as HashMap, TreeMap, etc.), a key can only correspond to one value, and it does not support multiple values ​​attached to a key.

However, if you want to implement a data structure where a key can be associated with multiple values, you can use some special implementation or extend the existing data structure. A common practice is to use a list (List) or collection (Set) to store multiple values, and associate this list or collection as a value with a key. This actually implements a one-to-many mapping relationship.

For example, you can use HashMapto implement a structure that can associate multiple values ​​with a key:

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

public class MultiValueMapExample {
    
    
    public static void main(String[] args) {
    
    
        Map<String, List<String>> multiValueMap = new HashMap<>();
        
        // 添加多个值到同一个键
        multiValueMap.put("key1", new ArrayList<>());
        multiValueMap.get("key1").add("value1");
        multiValueMap.get("key1").add("value2");
        
        // 获取键关联的多个值
        List<String> valuesForKey1 = multiValueMap.get("key1");
        System.out.println(valuesForKey1); // Output: [value1, value2]
    }
}

Guess you like

Origin blog.csdn.net/qq_41714549/article/details/132503460