这种类似Map的结构是否作为某些标准Collection的一部分存在?

时间:2014-06-24 20:46:39

标签: java collections map

我正在寻找一个像这样的

的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

2 个答案:

答案 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);