Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

update Map key's value java

Tags:

java

treemap

Ok I have this code:

TreeMap<DateTime, Integer> tree2 = getDatesTreeMap();
DateTime startx = new DateTime(startDate.getTime());
DateTime endx = new DateTime(endDate.getTime());
boolean possible = false;
int testValue = 0;
//produces submap
Map<DateTime, Integer> nav = tree2.subMap(startx, endx);

for (Integer capacity : tree2.subMap(startx, endx).values()) {
    //Provides an insight into capacity accomodation possibility
    //testValue++;
    terminals = 20;
    if(capacity >= terminals)
        possible = true;
    else if(capacity < terminals)
        possible = false;

}

if(possible == true)
{
    for (Integer capacity : tree2.subMap(startx, endx).values()) {
    {
        capacity -= terminals;
        //not sure what to do
    }
}
}else{

}

return possible;

It checks for range of date in submap. then checks if values of those dates (which are keys btw) can accomodate terminals (that is reservation number), then if yes it would subtract that from capacity currently in map. I am unsure how to update the capacity in the map for all dates between startx and endx with value

capacity -= terminals;

Thanks, :)

like image 209
sys_debug Avatar asked Nov 18 '11 10:11

sys_debug


People also ask

How do I change the key value of a map in Java?

The replace(K key, V value) method of Map interface, implemented by HashMap class is used to replace the value of the specified key only if the key is previously mapped with some value. Parameters: This method accepts two parameters: key: which is the key of the element whose value has to be replaced.

How do you update an existing map value?

You can use computeIfPresent method and supply it a mapping function, which will be called to compute a new value based on existing one. For example, Map<String, Integer> words = new HashMap<>(); words.

Can we update key in HashMap?

Increase the value of a key in HashMap 2.1 We can update or increase the value of a key with the below get() + 1 method. 2.2 However, the above method will throw a NullPointerException if the key doesn't exist. The fixed is uses the containsKey() to ensure the key exists before update the key's value.

Does map put overwrite?

Yes. If a mapping to the specified key already exists, the old value will be replaced (and returned).


1 Answers

You have to reinsert the key / value into the map with the updated value.

tree2.put(key, tree2.get(key) - terminals);
like image 89
aioobe Avatar answered Sep 21 '22 01:09

aioobe