Search code examples
javacollectionsguavaidentitymultimap

Is there IdentitySetMultimap in guava or somewhere else?


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.


Solution

  • 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.