The difference between put
and replace
is that put
always associates key with value - even if the key did not exist before. The replace
would then be a convenience method, so only change the value if the key is there - do nothing if the key does not exist.
(This is convenient, I do not know, but people who use a lot of Java must have gone through this situation several times, to find it helps ...)
forEach
was introduced in version 8 along with support for lambdas . Therefore, its form of use is through this abstraction. Example:
map.forEach((k, v) -> System.out.println(k + "=" + v));
(i.e. you create variables to represent the key and value, and set the code that will act on each key / value pair)
By the way, I realized now that replaceAll
" - and not the replace
- that receive BiFunction
as a parameter. Its use is to update not only one but all elements of a Map
:
map.replaceAll((k, v) -> v * v); // Substitui cada valor pelo seu quadrado
According to this post , "we often get a value of a map, we do some calculations about it and put it back on the map. The code can be wordy, and difficult to do properly if competition is involved. " These methods then serve to help in this: update a given value of Map
.
map.compute(minhaChave, (k, v) -> v * v); // Substitui o valor pelo seu quadrado
The computeIfPresent
does the same, but only when the key is already present in Map
( compute
does with or without the present key, passing null
value if the key is absent). Since computeIfAbsent
is the opposite - just in case the key is absent. In this case, as we already know that it has no value, it does not make sense for lambda to receive two parameters, so only the key is considered:
map.computeIfAbsent(minhaChave, (k) -> 42);