fr.vergne.collection.util.ReflexiveMap Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of collection-core Show documentation
Show all versions of collection-core Show documentation
Implementation of the collection facilities.
package fr.vergne.collection.util;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
/**
* A {@link ReflexiveMap} aims at providing a {@link Map} which support a
* bijective relation. In other words, the {@link Value} can be considered as a
* key for the {@link Key}. Such {@link Map} can thus be mirrored to be able to
* access {@link Key}s by providing the corresponding {@link Value}s. This is
* what is supported by the {@link #reverse()} method.
*
* @author Matthieu Vergne
*
* @param
* @param
*/
public class ReflexiveMap implements Map {
private final Map keyValue;
private final Map valueKey;
private final ReflexiveMap reversed;
public ReflexiveMap() {
keyValue = generateInternalMap();
valueKey = generateInternalMap();
reversed = new ReflexiveMap(this);
}
/**
* Internally, two different {@link Map}s are used to store the data. Each
* update on this {@link ReflexiveMap} correspond to an update to both these
* internal {@link Map}s. You can override this method to change the type of
* internal {@link Map} used.
*
* @return the type of map backed by this {@link ReflexiveMap}
*/
protected Map generateInternalMap() {
return new LinkedHashMap();
}
private ReflexiveMap(ReflexiveMap reflex) {
keyValue = reflex.valueKey;
valueKey = reflex.keyValue;
reversed = reflex;
}
@Override
public void clear() {
keyValue.clear();
valueKey.clear();
}
@Override
public boolean containsKey(Object key) {
return keyValue.containsKey(key);
}
@Override
public boolean containsValue(Object value) {
return keyValue.containsValue(value);
}
@Override
public Set> entrySet() {
return keyValue.entrySet();
}
@Override
public Value get(Object key) {
return keyValue.get(key);
}
public Value getValueFrom(Key key) {
return keyValue.get(key);
}
public Key getKeyFrom(Value value) {
return valueKey.get(value);
}
@Override
public boolean isEmpty() {
return keyValue.isEmpty();
}
@Override
public Set keySet() {
return keyValue.keySet();
}
@Override
public Value put(Key key, Value value) {
valueKey.remove(keyValue.get(key));
valueKey.put(value, key);
return keyValue.put(key, value);
}
@Override
public void putAll(Map extends Key, ? extends Value> m) {
for (Entry extends Key, ? extends Value> entry : m.entrySet()) {
put(entry.getKey(), entry.getValue());
}
}
@Override
public Value remove(Object key) {
Value removed = keyValue.remove(key);
valueKey.remove(removed);
return removed;
}
@Override
public int size() {
return keyValue.size();
}
@Override
public Collection values() {
return keyValue.values();
}
public ReflexiveMap reverse() {
return reversed;
}
@Override
public String toString() {
return keyValue.toString();
}
}