Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
367 views
in Technique[技术] by (71.8m points)

hashmap - Java many to many association map

I have two classes, ClassA and ClassB, as well as a "many to many" AssociationClass. I want a structure that holds the associations between A and B so that I can find the counterpart for each instance of A or B.

I thought of using a Hashmap, with pair keys:

Hasmap<Pair<ClassA, ClassB>, AssociationClass> associations;

This way, I can add and remove an association between two instances of ClassA and ClassB, and I can query a relation for two given instances.

However, I miss the feature of getting all associations defined for a given instance of ClassA or ClassB.

I could do it by brute force and loop over all keys of the map to search for associations between a given instance, but this is inefficient and not elegant.

Do you know of any data structure / free library that enables this? I don't want to reinvent the wheel.

NB: This is not a "database" question. These objects are pure POJO used for live computation, I don't need persistence stuff.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's my implementation based on guava Multimap:

public class ImmutableBiMultimap<K, V> {
    private final ImmutableSetMultimap<K, V> kToV;
    private final ImmutableSetMultimap<V, K> vToK;

    public ImmutableBiMultimap (SetMultimap<K, V> keyToValueMap) {
        kToV = ImmutableSetMultimap.copyOf(keyToValueMap);

        SetMultimap<V, K> valueToKeyMap = HashMultimap.create();
        for (Entry<K, V> entry : kToV.entries()) {
            valueToKeyMap.put(entry.getValue(), entry.getKey());
        }

        vToK = ImmutableSetMultimap.copyOf(valueToKeyMap);
    }

    public ImmutableSet<V> getValuesForKey(K key) {
        return kToV.get(key);
    }

    public ImmutableSet<K> getKeysForValue(V value) {
        return vToK.get(value);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...