
com.magictools.core.map.BiMap Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of magic-tools-all Show documentation
Show all versions of magic-tools-all Show documentation
magic-tools 是一个小而全的Java工具类库,通过静态方法封装,降低相关API的学习成本,提高工作效率,使Java拥有函数式语言般的优雅,让Java语言也可以“甜甜的”。
The newest version!
package com.magictools.core.map;
import java.util.Map;
/**
* 双向Map
* 互换键值对不检查值是否有重复,如果有则后加入的元素替换先加入的元素
* 值的顺序在HashMap中不确定,所以谁覆盖谁也不确定,在有序的Map中按照先后顺序覆盖,保留最后的值
* 它与TableMap的区别是,BiMap维护两个Map实现高效的正向和反向查找
*
* @param 键类型
* @param 值类型
* @since 5.2.6
*/
public class BiMap extends MapWrapper {
private static final long serialVersionUID = 1L;
private Map inverse;
/**
* 构造
*
* @param raw 被包装的Map
*/
public BiMap(Map raw) {
super(raw);
}
@Override
public V put(K key, V value) {
if (null != this.inverse) {
this.inverse.put(value, key);
}
return super.put(key, value);
}
@Override
public void putAll(Map extends K, ? extends V> m) {
super.putAll(m);
if (null != this.inverse) {
m.forEach((key, value) -> this.inverse.put(value, key));
}
}
@Override
public V remove(Object key) {
final V v = super.remove(key);
if(null != this.inverse && null != v){
this.inverse.remove(v);
}
return v;
}
@Override
public boolean remove(Object key, Object value) {
return super.remove(key, value) && null != this.inverse && this.inverse.remove(value, key);
}
@Override
public void clear() {
super.clear();
this.inverse = null;
}
/**
* 获取反向Map
*
* @return 反向Map
*/
public Map getInverse() {
if (null == this.inverse) {
inverse = MapUtil.inverse(getRaw());
}
return this.inverse;
}
/**
* 根据值获得键
*
* @param value 值
* @return 键
*/
public K getKey(V value) {
return getInverse().get(value);
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy