Created
May 27, 2016 06:00
-
-
Save SpaceBison/b2acd70c9fc1cc545d1a86cd5c08017d to your computer and use it in GitHub Desktop.
BiMap - java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Bi-directional {@link Map}. Provides one-to-one mapping of keys and values. | |
*/ | |
public class BiMap <K,V> implements Map<K,V> { | |
private final HashMap<K,V> mMap = new HashMap<>(); | |
private final HashMap<V,K> mReverseMap = new HashMap<>(); | |
@Override | |
public void clear() { | |
mMap.clear(); | |
mReverseMap.clear(); | |
} | |
@Override | |
public boolean containsKey(Object key) { | |
return mMap.containsKey(key); | |
} | |
@Override | |
public boolean containsValue(Object value) { | |
return mMap.containsValue(value); | |
} | |
@NonNull | |
@Override | |
public Set<Entry<K, V>> entrySet() { | |
return mMap.entrySet(); | |
} | |
@Override | |
public V get(Object key) { | |
return mMap.get(key); | |
} | |
/** | |
* Returns the value of the reverse mapping with the specified value. | |
* | |
* @param value the value. | |
* @return the value of the mapping with the specified key, or null if no mapping for the specified key is found. | |
*/ | |
public K reverseGet(Object value) { | |
return mReverseMap.get(value); | |
} | |
@Override | |
public boolean isEmpty() { | |
return mMap.isEmpty(); | |
} | |
@NonNull | |
@Override | |
public Set<K> keySet() { | |
return mMap.keySet(); | |
} | |
/** | |
* Creates a two-way mapping between the key and the value. | |
* | |
* @param key the key | |
* @param value the value | |
* @return The previous value that was mapped to the key or null if there was none. | |
*/ | |
@Override | |
public V put(K key, V value) { | |
K previousKey = mReverseMap.put(value, key); | |
if (previousKey != null) { | |
mMap.remove(previousKey); | |
} | |
return mMap.put(key, value); | |
} | |
@Override | |
public void putAll(@NonNull Map<? extends K, ? extends V> map) { | |
for (Entry<? extends K, ? extends V> e : map.entrySet()) { | |
put(e.getKey(), e.getValue()); | |
} | |
} | |
@Override | |
public V remove(Object key) { | |
V removedValue = mMap.remove(key); | |
if (removedValue != null) { | |
mReverseMap.remove(removedValue); | |
} | |
return removedValue; | |
} | |
@Override | |
public int size() { | |
return mMap.size(); | |
} | |
@NonNull | |
@Override | |
public Collection<V> values() { | |
return mReverseMap.keySet(); | |
} | |
/** | |
* Returns a copy of the map with keys and values swapped. | |
* | |
* @return reversed map. | |
*/ | |
public Map<V,K> reverseMap() { | |
return new HashMap<>(mReverseMap); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment