Collection Map<k,v> Methods

Asked

Viewed 315 times

2

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

  1. The replace is it really necessary? this is me whenever I wanted to replace a Value of a Key I was doing the put, as the key was the same map itself replaced. With this implementation I may have problems?
  2. forEach I know it serves to go through the map doing actions but how I implement the input parameter(according to the documentation BiConsumer<? super K,? super V> action) may pass an example?
  3. The compute : computeIfAbsent : computeIfPresent I couldn’t figure out what they serve to give an example of use?

1 answer

2


  1. The difference between the put and the replace is that the put always associates the key to the value - even if the key did not exist before. O replace would then be a method of convenience, only to change the value if the key is there - do nothing if the key does not exist.

    (in what this is convenient, I do not know, but who uses a lot of Java must have gone through this situation several times, to find that it helps...)

  2. The forEachwas introduced in version 8 along with support for Amble. Thus, 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 the value, and establish the code that will act on each key/value pair)

    By the way, I just realized that you are replaceAll - and not the replace - who receive a BiFunction as parameter. Its use is to update not only one, but all the elements of a Map:

    map.replaceAll((k, v) -> v * v); // Substitui cada valor pelo seu quadrado
    
  3. According to that post, "Often we take a value from a map, do some calculations on it and put it back into the map. The code can be long-winded, and difficult to do properly if competition is involved." These methods then serve to help in this: updating a certain value of the 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 the Map (the compute does with or without the gift key, passing a value null if the key is missing). Already the computeIfAbsent is the opposite - just in case the key is missing. In this case, as we already know that it has no value, it makes no sense to lambda receive two parameters, so only the key is considered:

    map.computeIfAbsent(minhaChave, (k) -> 42);
    

Browser other questions tagged

You are not signed in. Login or sign up in order to post.