简体   繁体   English

从番石榴(谷歌)Multimap 中删除永远不会删除密钥本身。 为什么? 怎么做?

[英]Removing from guava (google) Multimap never removes the key itself. Why? How to do so?

I'm using the google collections library from guava, I believe the most recent version.我正在使用来自番石榴的谷歌 collections 库,我相信是最新版本。

I find that once I remove the final (K, V) pair from the map for a given value of K, the map still contains an entry for K, where V is an empty collection.我发现一旦我从 map 中删除给定 K 值的最后一个 (K, V) 对,map 仍然包含 K 的条目,其中 V 是一个空集合。

I would rather have the map not contain this entry.我宁愿 map 不包含此条目。 Why can't I remove it?为什么我不能删除它? Or, if I can, how?或者,如果可以,怎么做?

It's probably something simple that I have missed.这可能是我错过的一些简单的事情。 Here is a code example.这是一个代码示例。 Thanks.谢谢。

    // A plain ordinary map.
    Map<Integer, Integer> hm = new HashMap<Integer, Integer>();
    hm.put(1, 2);
    hm.remove(1);
    // Value of key 1 in HashMap: null
    System.out.println("Value of key 1 in HashMap: " + hm.get(1));

    // A list multimap.
    ListMultimap<Integer, Integer> lmm = ArrayListMultimap.<Integer, Integer> create();
    lmm.put(1, 2);
    lmm.remove(1, 2);
    // Value of key 1 in ArrayListMultiMap: []
    System.out.println("Value of key 1 in ArrayListMultiMap: " + lmm.get(1));

    // A set multimap.
    SetMultimap<Integer, Integer> smm = HashMultimap.<Integer, Integer> create();
    smm.put(1, 2);
    smm.remove(1, 2);
    // Value of key 1 in HashMultimap: []
    System.out.println("Value of key 1 in HashMultimap: " + smm.get(1));

Actually when you remove the last value for a key in the multimap, the key is removed from the map.实际上,当您删除多图中某个键的最后一个值时,该键将从 map 中删除。 See for instance the behaviour of 'containsKey'参见例如“containsKey”的行为

System.out.println("ListMultimap contains key 1? " + lmm.containsKey(1));

However when you get the values from the multimap, if there is no collection associated with the key, it will return an empty collection, see the implementation of get in AbstractMultimap:但是当你从multimap中获取值时,如果没有与key关联的集合,它会返回一个空集合,参见AbstractMultimap中get的实现:

/**
 * {@inheritDoc}
 *
 * <p>The returned collection is not serializable.
 */
@Override
public Collection<V> get(@Nullable K key) {
  Collection<V> collection = map.get(key);
  if (collection == null) {
    collection = createCollection(key);
  }
  return wrapCollection(key, collection);
}

To totally remove the underlying entry from the Multimap , you need to use the Map view:要从Multimap中完全删除底层条目,您需要使用Map视图:

multimap.asMap().remove(key);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM