I want to make a histogram by using a HashMap
, the key should be the delay, the value the amount of times this delay occurs. I am doubting to use the HashMap
replace
or the HashMap
put
function if an already existing delay has an new occurence. I did it by this way:
int delay = (int) (loopcount-packetServed.getArrivalTime()); if(histogramType1.containsKey(delay)) { histogramType1.replace(delay, histogramType1.get(delay) + 1); } else { histogramType1.put(delay, 1); }
Is this correct? or should I use two times the put function?
Yes. If a mapping to the specified key already exists, the old value will be replaced (and returned). See Hashtable.
You cannot rename/modify the hashmap key once added. Only way is to delete/remove the key and insert with new key and value pair. Reason : In hashmap internal implementation the Hashmap key modifier marked as final . this is the best answer in my opinion since it's not possible to rename a key.
HashMap stores key, value pairs and it does not allow duplicate keys. If the key is duplicate then the old key is replaced with the new value.
There is absolutely no difference in put
and replace
when there is a current mapping for the wanted key. From replace
:
Replaces the entry for the specified key only if it is currently mapped to some value.
This means that if there is already a mapping for the given key, both put
and replace
will update the map in the same way. Both will also return the previous value associated with the key. However, if there is no mapping for that key, then replace
will be a no-op (will do nothing) whereas put
will still update the map.
Starting with Java 8, note that you can just use
histogramType1.merge(delay, 1, Integer::sum);
This will take care of every condition. From merge
:
If the specified key is not already associated with a value or is associated with
null
, associates it with the given non-null value. Otherwise, replaces the associated value with the results of the given remapping function, or removes if the result isnull
.
In this case, we are creating the entry delay -> 1
if the entry didn't exist. If it did exist, it is updated by incrementing the value by 1.
In your case, since you first check if the value is contained in the map, using put
or replace
leads to the same result.
You can use either, based on what is more readable to you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With