5

我正在使用来自 guava 的 google 收藏库,我相信是最新版本。

我发现一旦我从映射中删除给定 K 值的最后一个 (K, V) 对,映射仍然包含 K 的条目,其中 V 是一个空集合。

我宁愿地图不包含此条目。为什么我不能删除它?或者,如果可以,怎么做?

这可能是我错过的一些简单的事情。这是一个代码示例。谢谢。

    // 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));
4

2 回答 2

7

实际上,当您删除多映射中某个键的最后一个值时,该键将从映射中删除。参见例如“containsKey”的行为

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

但是当你从多映射中获取值时,如果没有与该键关联的集合,它将返回一个空集合,请参见 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);
}
于 2011-11-28T13:17:34.613 回答
5

要从 中完全删除底层条目Multimap,您需要使用Map视图:

multimap.asMap().remove(key);
于 2011-11-28T13:11:44.720 回答