简体   繁体   English

在地图中检查密钥,增加新的密钥值并添加回地图

[英]Checking key in a map, increment the new key value and add back to the map

I have entries in a LinkedHashMap<Integer,String> like: 我在LinkedHashMap<Integer,String>有条目,例如:

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

The integer values are based on some hierarchy. 整数值基于某些层次结构。 Is there a way for me to check what was the last key in the 3000 or 2000 series in the map was so that my new key can be an increment of that? 我是否可以检查地图中3000或2000系列的最后一个键是什么,以便我的新键可以是该键的增量? Eg If I need to make a new entry down the line at the 2000 hierarchy level and the last key was 2015, how can I check this and increment my new key to 2016 and add to the map. 例如,如果我需要在2000层次结构级别下一行中输入一个新条目,而最后一个键是2015,那么如何检查此并将新键增加到2016,然后添加到地图中。

You could use the streams API on the keyset like this: 您可以像这样在键集上使用流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());
    }

This returns an optional since you can't be sure that there is already a value in the series. 这将返回一个可选值,因为您不能确保该系列中已经有一个值。

You can store the last key and increment it after adding new element or find it this way: 您可以存储最后一个键,并在添加新元素后递增或以这种方式找到它:

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

keySet() method of LinkedHashMap also might be helpful. LinkedHashMap keySet()方法也可能会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM