Multimaps [overview, applicable scenarios, java demo]

15674004:

overview

        MultimapsIt is a tool class provided by Google Guava, which is used to process the data structure of multi-value mapping. It provides a convenient way to create and manipulate multi-valued maps, where each key can be associated with one or more values.

Functions: MultimapsProvides the following main functions:

  1. Associate multiple values ​​with a single key.
  2. Get all values ​​associated with a given key.
  3. Get a collection containing all key-value pairs.
  4. Get all keys.
  5. Get all values.
  6. Removes all values ​​associated with the given key.

Applicable scene

MultimapsApplies to the following scenarios:

  1. A key can have multiple values ​​associated with it, such as a student can have multiple courses.
  2. Handle the needs of multi-valued mappings without writing complex data structures or logic yourself.
  3. Operations that need to handle multi-value maps quickly and easily, such as add, get, remove, etc.

Java example

        Here's a MultimapsJava example using :

javaCopy code
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;

public class MultimapExample {
    
    
    public static void main(String[] args) {
    
    
        // 创建一个 ArrayListMultimap 实例
        Multimap<String, Integer> multimap = ArrayListMultimap.create();

        // 添加键值对
        multimap.put("key1", 1);
        multimap.put("key1", 2);
        multimap.put("key2", 3);
        multimap.put("key2", 4);
        multimap.put("key2", 5);

        // 获取给定键关联的所有值
        System.out.println(multimap.get("key1")); // 输出: [1, 2]
        System.out.println(multimap.get("key2")); // 输出: [3, 4, 5]

        // 获取所有的键
        System.out.println(multimap.keys()); // 输出: [key1 x 2, key2 x 3]

        // 获取所有的值
        System.out.println(multimap.values()); // 输出: [1, 2, 3, 4, 5]

        // 移除给定键关联的所有值
        multimap.removeAll("key1");
        System.out.println(multimap.get("key1")); // 输出: []

        // 移除所有的键值对
        multimap.clear();
        System.out.println(multimap.isEmpty()); // 输出: true
    }
}

Guess you like

Origin blog.csdn.net/asd1358355022/article/details/131328584