简体   繁体   中英

Data structure having two keys in java

I have a following scenario.

1) Module A sends parameter to Modele B, and then Module B makes a request to Module C to provide values for that parameter. (There can be many requesters ie Module A1,A2 etc. as Module A). The Module C then sends the parameter value to Module B, and then Module B sends the values back to the Module A. Thus Module B is a middleware.

2) Here Module B gives a unique intKey to each requesters (to Module A1,A2 etc.) And Module C gives unique StringKey per requester to the Module B.

3) Module B is responsible to give correct values to correct requester. That means it has to map StringKey to intKey. Currently it does so by creating two concurrent hashmaps. i) intKey,StringKey and ii) StringKey,intKey

The problem now is that the Module B has to all the time iterate over the Maps to find the correct requester (Module A).

I was wondering if I can have a data structure where I have two keys and if I give any one say Key1 then I can retrieve its corresponding key2 and also the other way. Is there any way I can get rid of these two concurrent Hashmaps ? I would highly appreciate any help regarding this.

Essentially no - you cannot get away from using two maps, concurrent or otherwise, because you are working with two different types of key (unless you decide to use Map<Object,Object> which would be criminal).

But - you can hide the complexity:

public interface BiMap<P, Q> {

    public Q putQ(P key, Q value);

    public Q getQ(P key);

    public P putP(P key, Q value);

    public P getP(Q key);
}

Now wrap your two maps in one of those and things look tidier, they just aren't tidy inside.

This should work:

public class BiMap<P, Q> {

    final Map<P, Q> pq;
    final Map<Q, P> qp;

    public BiMap(MapFactory maker) {
        pq = maker.<P, Q>make();
        qp = maker.<Q, P>make();
    }

    public BiMap() {
        // Default to ConcurrentHashMap
        this(MapFactory.ConcurrentHashMap);
    }

    public Q putQ(P key, Q value) {
        return pq.put(key, value);
    }

    public Q getQ(P key) {
        return pq.get(key);
    }

    public P putP(Q key, P value) {
        return qp.put(key, value);
    }

    public P getP(Q key) {
        return qp.get(key);
    }

    // Puts both at once.
    public synchronized void put(P p, Q q) {
        putQ(p, q);
        putP(q, p);
    }

    public enum MapFactory {

        ConcurrentHashMap {

                    @Override
                    <P, Q> Map<P, Q> make() {
                        return new java.util.concurrent.ConcurrentHashMap<P,Q>();
                    }

                };

        abstract <P, Q> Map<P, Q> make();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM