4

Java provides IdentityHashMap which is perfect when you want to compare objects by == instead of equals method.

Guava provides nice wrapper for Map<Key, Set<Value> which is SetMultimap. However there are no implementation of it which uses identity object comparison (==).

Is there anything better than plain IdentityHashMap<Key, IdentityHashSet<Value>>? SomeIdentitySetMultimap<Key, Value> would be ideal.

kokosing
  • 5,251
  • 5
  • 37
  • 50

3 Answers3

9

You can use Multimaps.newSetMultimap(Map, Supplier) with Maps.newIdentityHashMap() and Sets.newIdentityHashSet():

public static <K, V> SetMultimap<K, V> newIdentitySetMultimap() {
    return Multimaps.newSetMultimap(Maps.newIdentityHashMap(), Sets::newIdentityHashSet);
}

This also gives you the ability to use identity comparison for only the keys or only the values by specifying a different map or set implementation. The example above will use identity comparison for both.

mfulton26
  • 29,956
  • 6
  • 64
  • 88
4

With Eclipse Collections you can currently have an identity set for the values, but not an identity map for the keys (as of today). The following would work if all you need is for identity set for the values.

MutableSetMultimap<String, String> multimap =
    UnifiedSetWithHashingStrategyMultimap.newMultimap(
        HashingStrategies.identityStrategy());
multimap.put("a", "a");
multimap.put("a", new String("a"));
multimap.put("a", new String("a"));

Assert.assertEquals(3, multimap.get("a").size());

You can also define your own HashingStrategy implementations for use with UnifiedSetWithHashingStrategyMultimap.

Note: I am a committer for Eclipse Collections.

Donald Raab
  • 6,458
  • 2
  • 36
  • 44
2

Guava doesn't have IdentitySetMultimap. We generally recommend either that you do what you've proposed or that you create a SetMultimap<Equivalence.Wrapper<Key>, Equivalence.Wrapper<Value>>. You would use Equivalence.identity().wrap(...) to wrap your keys and values before querying/modifying the collection.

(Update: You can see from another answer that there's another way to do this.)

Community
  • 1
  • 1
Chris Povirk
  • 3,738
  • 3
  • 29
  • 47