我正在寻找一个像这样的
的Map结构public MapBiggest<K,V implements Comparable> extends Map<K,V implements Comparable>{
@override
public V put(K key, V value){
T currentValue = null;
// Insert in one of two cases
if((currentValue = this.get(key)) == null || // case1: key isn't in map
value.compareTo(currentValue)>0){ // case2: new value is > currentValue
return super.put(key,value);
}
return currentValue;
}
}
也就是说,您可以继续插入项目,并且会有一些逻辑(Comparator
)决定保留哪些元素。
感谢。
(注意,此代码均未编译)
编辑#1:点击返回V
答案 0 :(得分:2)
这个怎么样:
public MapBiggest<K, V implements Comparable> {
final Map<K, V,> backingMap //in the constructor you say new HashMap<>();
public V put(K key, V value){
final V currentValue = backingMap.get(key);
if(currentValue == null || currentValue.compareTo(value) < 0) {
return backingMap.put(key, value);
}
return currentValue;
}
}
答案 1 :(得分:2)
在Java 8中,这可能只是
map.merge(key, value, (left, right) -> left.compare(right) > 0 ? left : right);