-1

Is there a collection that works in the following way:

//when

value1 -> value2 
value3 -> value4

//so that

value2 is the opposite of value1
and
value4 is the opposite of value3

//then The requests should work as follows:

request in:value1 return out:value2
request in:value2 return out:value1

etc

I guess I can do this with functions but wondering if there is specialised collection for this.

jakstack
  • 2,143
  • 3
  • 20
  • 37
  • 2
    what does value1 -> value2 mean? I find this question unclear. – JensW Apr 30 '19 at 14:01
  • If this is just data that you prepare in advance, you can probably just create a Map and put the entries in using two `put` operations for each pair. But if you need a full API, I believe you'll have to write a more comprehensive wrapper. – RealSkeptic Apr 30 '19 at 14:05
  • What's the connection between a collection class and inverted values? – Joakim Danielson Apr 30 '19 at 14:07

1 Answers1

2

You seem to be looking for an invertable mapping. This has been discussed in some detail already: Java invert map.

One of the links from that prior discussion is to an Apache solution: https://commons.apache.org/proper/commons-collections/javadocs/api-3.2.2/org/apache/commons/collections/BidiMap.html.

While java doesn't have a collection type which handles this efficiently, you can make one yourself by putting together two maps:

public class BiDiMap<T1, T2> {
    private final Map<T1, T2> forwardMap = new HashMap<T1, T2>();
    private final Map<T2, T1> reverseMap = new HashMap<T2, T1>();

    public void put(T1 t1, T2 t2) {
        T2 oldT2 = forwardMap.put(t1, t2);
        T1 oldT1 = reverseMap.put(t2, t1);
    }
    public void remove(T1 t1, T2 t2) {
        T2 currentT2 = forwardMap.get(t1);
        if ( currentT2 != t2 ) {
            // This is an error.
        }
        T1 currentT1 = reverseMap.get(t2);
        if ( currentT1 != t1 ) {
            // Also an error.
        }
        forwardMap.remove(t1);
        reverseMap.remove(t2);
    }
    public T2 getForward(T1 t1) {
        return forwardMap.get(t1);
    }
    public T1 getReverse(T2 t2) {
        return reverseMap.get(t2);
    }
}

And so on.

This assumes that the mapping is one-to-one. The implementation is different if the mapping is one-to-many, many-to-one, or many-to-many.

Thomas Bitonti
  • 1,179
  • 7
  • 14