Mapk Collection, v Methods

2

Doubts about methods replace : compute : computeIfAbsent : computeIfPresent : forEach (briefly all that use function or biFuntion within input parameter)

  • Is replace really necessary? this is me whenever I wanted to replace a Value of a Key I made put , as the key was the same the map itself replaced. With this implementation can I have problems?
  • forEach I know how to go through the whole map doing actions but how to implement the input parameter ( according to the documentation BiConsumer<? super K,? super V> action ) can you pass an example?
  • The compute : computeIfAbsent : computeIfPresent could not understand what they are for can they give an example of use?
  • asked by anonymous 22.08.2014 / 15:21

    1 answer

    2
  • 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);
    
  • 22.08.2014 / 15:42