Java 8 Map : computeIfPresent

computeIfPresent()


default V computeIfPresent(K key, BiFunction<? super K,? super V,? extends V> remappingFunction)

If the value for the specified key is present and non-null, it attempts to compute a new mapping given the key and its current mapped value.
If the function returns null, the mapping is removed.

computeIfPresent() uses a BiFunction . The Function runs only if the specified key is present in the map.

package com.topjavatutorial;

import java.util.HashMap;
import java.util.Map;
import java.util.function.BiFunction;

public class TestMap2 {

  public static void main(String[] args) {
    Map<String, Integer> map = new HashMap<String, Integer>();
    map.put("A", 1);
    map.put("B", 2);
    map.put("C", 3);
    System.out.println(map);

    BiFunction<String, Integer, Integer> biFunction = (k, v) -> v + 1;

    // "A" is already present in map, so its value will be incremented
    map.computeIfPresent("A", biFunction);
    System.out.println(map);

    // Since "D" is not present in map, the computation won't occur
    map.computeIfPresent("D", biFunction);
    System.out.println(map);
  }

}

Output :

{A=1, B=2, C=3}
{A=2, B=2, C=3}
{A=2, B=2, C=3}
 

Similar articles

© 2017 – 2018, https:. All rights reserved. On republishing this post, you must provide link to original post

You may also like...

Leave a Reply.. code can be added in <code> </code> tags