【问题标题】:Checking key in a map, increment the new key value and add back to the map检查地图中的键,增加新的键值并添加回地图
【发布时间】:2017-11-06 15:05:44
【问题描述】:

我在LinkedHashMap<Integer,String> 中有条目,例如:

1000 Coffee
2000 Source
3000 Legends
4000 Kaldi
4001 Sheikh Omar
3001 Transmission

整数值基于某些层次结构。有没有办法让我检查地图中 3000 或 2000 系列中的最后一个键是什么,以便我的新键可以增加它?例如。如果我需要在 2000 层次结构级别下创建一个新条目并且最后一个键是 2015,我该如何检查这个并将我的新键增加到 2016 并添加到地图中。

【问题讨论】:

  • 您可能不想麻烦自己,而是使用(排序的)TreeMap

标签: java maps


【解决方案1】:

您可以像这样在密钥集上使用流 API:

 //floor is the start of the series, ceiling is the start of the next one.
 public Optional<Integer> getLastInSeries(int floor, int ceiling, LinkedHashMap<Integer, String> linkedHashMap) {
        return linkedHashMap.keySet().stream()
                .filter(integer -> integer < ceiling && integer > floor)
                .max(Comparator.naturalOrder());
    }

这将返回一个可选值,因为您无法确定该系列中已经存在一个值。

【讨论】:

    【解决方案2】:

    您可以存储最后一个键并在添加新元素后递增它或通过这种方式找到它:

    public int getLastKey(int series, LinkedHashMap map) {
        for(int i = 0; i < 1000; i++) {
            if (map.get(series + i) == null) {
                return series + i;
    }
    

    LinkedHashMapkeySet() 方法也可能有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-07
      • 1970-01-01
      • 2012-10-22
      • 2019-05-27
      • 1970-01-01
      • 2013-04-06
      • 1970-01-01
      相关资源
      最近更新 更多