Reputation: 127
Is there some type of map implementation that supports 2 separate keys?
For example you would do something like put(Int, String, Value)
and then you'd later be able to use get the value based on the Integer or the String independently. Currently I am just using 2 Maps but it seems like there would be a better way to do this.
Upvotes: 1
Views: 84
Reputation: 425013
Use a Map<Object, MyValueClass>
and store the value under both keys.
If you really want a class:
public class DoubleKeyMap<T> extends HashMap<Object, T> {
public void put(Object key1, Object key2, T value) {
put(key1, value);
put(key2, value);
}
}
The value can now be found under either key.
Upvotes: 0
Reputation: 11347
To answer your question: No.
You could roll it yourself:
class MyDataStore<T> {
private final Map<Integer, T> intMap = new HashMap<>();
private final Map<String, T> stringMap = new HashMap<>();
public void put(Integer keyI, String keyS, T datum) {
intMap.put(keyI, datum);
stringMap.put(keyS, datum);
}
public void remove(T datum) {
intMap.remove(datum);
stringMap.remove(datum);
}
public Map<Integer, T> asIntMap() {return Collections.unmodifiableMap(intMap);}
public Map<String, T> asStringMap() {return Collections.unmodifiableMap(stringMap);}
}
Though a lot depends upon your use case. Maybe it's ok to key by one thing, and do an incremental search for the other? Especially if you don't actually have many elements.
Upvotes: 4