overview
Multimaps
It 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: Multimaps
Provides the following main functions:
- Associate multiple values with a single key.
- Get all values associated with a given key.
- Get a collection containing all key-value pairs.
- Get all keys.
- Get all values.
- Removes all values associated with the given key.
Applicable scene
Multimaps
Applies to the following scenarios:
- A key can have multiple values associated with it, such as a student can have multiple courses.
- Handle the needs of multi-valued mappings without writing complex data structures or logic yourself.
- Operations that need to handle multi-value maps quickly and easily, such as add, get, remove, etc.
Java example
Here's a Multimaps
Java 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
}
}