5

私はグアバのグーグルコレクションライブラリを使用しています。最新バージョンだと思います。

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 に答える