Guava之ArrayListMultimap

本文介绍ArrayListMultimap,一种使用ArrayList存储相同键多个值的多映射实现。文章详细阐述了其内部结构、常用方法及其与传统HashMap的区别,并通过示例展示了如何使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Class

ArrayListMultimap

All Implemented Interfaces

ListMultimap

简介

Implementation of Multimap that uses an ArrayList to store the values for a given key. A HashMap associates each key with an ArrayList of values.When iterating through the collections supplied by this class, the ordering of values for a given key agrees with the order in which the values were added.This multimap allows duplicate key-value pairs. After adding a new key-value pair equal to an existing key-value pair, the ArrayListMultimap will contain entries for both the new value and the old value.Keys and values may be null. All optional multimap methods are supported, and all returned views are modifiable.The lists returned by get(K), removeAll(java.lang.Object), and replaceValues(K, java.lang.Iterable

简言之

ArrayListMultimap底层可以认为是Map<K, Collection<V>>, 且key可以重复

常用方法

boolean      put(K key, V value)

说明: Stores a key-value pair in the multimap.

List<V>      get(K key)

说明: Returns a view collection of the values associated with key in this multimap, if any.

Map<K,Collection<V>>    asMap()

说明: Returns a view of this multimap as a Map from each distinct key to the nonempty collection of that key’s associated values.

Collection<Map.Entry<K,V>>    entries()

说明: Returns a view collection of all key-value pairs contained in this multimap, as Map.Entry instances.

boolean     containsEntry(Object key, Object value)

说明: Returns true if this multimap contains at least one key-value pair with the key key and the value value.

boolean     containsKey(Object key)

说明: Returns true if this multimap contains at least one key-value pair with the key key.

boolean     containsValue(Object value)

说明: Returns true if this multimap contains at least one key-value pair with the value value.

int     size()

说明: Returns the number of key-value pairs in this multimap.

Multiset<K>     keys()

说明: Returns a view collection containing the key from each key-value pair in this multimap, without collapsing duplicates.

Collection<V>    values()

说明: Returns a view collection containing the value from each key-value pair contained in this multimap, without collapsing duplicates (so values().size() == size()).

使用场景及示例

//传统的场景:  Map<String,List<MyClass>> map = new HashMap<String,List<MyClass>>();   

#缺点:向map里面添加元素不太方便,需要这样实现

    void putMyObject(String key, Object value) {
        List<Object> myClassList = myClassListMap.get(key);
        if(myClassList == null) {
            myClassList = new ArrayList<object>();
            myClassListMap.put(key,myClassList);
        }
        myClassList.add(value);
    }

    //补充: HashMap的key和value皆可为null,HashTable的key和value皆不可为null. 二者的key皆不可重复,若重复,后添加的会覆盖之前的.


//上面传统的场景,可以使用ArrayListMultimap  

Multimap<String, String> multimap = ArrayListMultimap.create();
multimap.put("fruit", "bannana");
multimap.put("fruit", "apple");//key可以重复
multimap.put("fruit", "apple");//value可以重复,不会覆盖之前的
multimap.put("fruit", "peach");
multimap.put("fish","crucian");//欧洲鲫鱼
multimap.put("fish","carp");//鲤鱼

System.err.println(multimap.size());//6

Collection<String> fruits = multimap.get("fruit");
System.err.println(fruits);//[bannana, apple, apple, peach]

for (String s : multimap.values()) {
    System.err.print(s + " , ");//bannana , apple , apple , peach , crucian , carp ,
}

multimap.remove("fruit","apple");
System.err.println(fruits);//[bannana, apple, peach]   注意:这里只remove了一个apple,因此还有一个apple

multimap.removeAll("fruit");
System.err.println(fruits);//[]


#TODO: 如果将multimap 直接返回前端, 返回的数据是 {"empty":false} , 是否可以返回给前端,Lifu不清楚

//get(key) 返回的是collection,如果希望返回的是list,可以选择ListMultimap来接收create()的返回值

    ListMultimap<String, String> listMultimap = ArrayListMultimap.create();
    listMultimap.put("fruit", "bannana");
    listMultimap.put("fruit", "apple");
    listMultimap.put("fruit", "peach");
    listMultimap.put("fish","crucian");//欧洲鲫鱼
    listMultimap.put("fish","carp");//鲤鱼

    List<String> fruits = listMultimap.get("fruit");
    System.err.println(fruits);//[bannana, apple, peach]



//对比 HashMultimap

    Multimap<String,String> multimap= HashMultimap.create();
    multimap.put("fruit", "bannana");
    multimap.put("fruit", "apple");
    multimap.put("fruit", "apple");

    System.err.println(multimap.size());//2
    System.err.println(multimap.get("fruit"));//[apple, bannana]     注意: 这里只有一个apple
### ArrayListMultimap in Java Guava Library `ArrayListMultimap` 是 Google 的 Guava 库中提供的一种 `Multimap` 实现。它允许多个值与同一个键关联,内部使用 `ArrayList` 来存储每个键的多个值[^4]。 以下是关于如何在 Java 中使用 `ArrayListMultimap` 的详细说明: #### 创建和初始化 ArrayListMultimap 可以通过 `ArrayListMultimap.create()` 方法创建一个 `ArrayListMultimap` 实例。以下是一个示例代码块: ```java import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; public class Main { public static void main(String[] args) { // 创建一个 ArrayListMultimap 实例 Multimap<String, String> multimap = ArrayListMultimap.create(); // 添加键值对 multimap.put("fruit", "apple"); multimap.put("fruit", "banana"); multimap.put("vegetable", "carrot"); } } ``` #### 添加和获取值 - 使用 `put(K key, V value)` 方法向 `ArrayListMultimap` 中添加键值对。 - 使用 `get(K key)` 方法获取与指定键关联的所有值的集合。 示例代码如下: ```java import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; import java.util.Collection; public class Main { public static void main(String[] args) { Multimap<String, String> multimap = ArrayListMultimap.create(); // 添加键值对 multimap.put("colors", "red"); multimap.put("colors", "green"); multimap.put("colors", "blue"); // 获取与键 "colors" 关联的所有值 Collection<String> colors = multimap.get("colors"); System.out.println(colors); // 输出: [red, green, blue] } } ``` #### 遍历 ArrayListMultimap 可以使用增强型 `for` 循环或迭代器遍历 `ArrayListMultimap` 中的所有键值对。 示例代码如下: ```java import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; public class Main { public static void main(String[] args) { Multimap<String, String> multimap = ArrayListMultimap.create(); // 添加键值对 multimap.put("languages", "Java"); multimap.put("languages", "Python"); multimap.put("languages", "C++"); // 遍历所有键值对 for (String key : multimap.keySet()) { System.out.println("Key: " + key); for (String value : multimap.get(key)) { System.out.println(" Value: " + value); } } } } ``` #### 删除键值对 可以使用 `remove(K key, V value)` 方法删除特定的键值对,或者使用 ` removeAll(K key)` 方法删除与某个键关联的所有值。 示例代码如下: ```java import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; public class Main { public static void main(String[] args) { Multimap<String, String> multimap = ArrayListMultimap.create(); // 添加键值对 multimap.put("numbers", "one"); multimap.put("numbers", "two"); multimap.put("numbers", "three"); // 删除特定键值对 multimap.remove("numbers", "two"); // 删除与键 "numbers" 关联的所有值 multimap.removeAll("numbers"); } } ``` ### 注意事项 - `ArrayListMultimap` 的值集合是可变的,并且允许重复值[^4]。 - 如果需要不可变的 `Multimap`,可以考虑使用 Guava 提供的 `ImmutableListMultimap`。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值