Java 8 Map : computeIfAbsent

computeIfAbsent

Syntax :


default V computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction)

If the specified key is not already associated with a value (or is mapped to null), attempts to compute its value using the given mapping function and enters it into this map unless null.

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

package com.topjavatutorial;

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

public class TestMap3 {

  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);

    Function<String, Integer> function = (k) -> 0;

    // "A" is already present in map, so the function will be skipped
    map.computeIfAbsent("A", function);
    System.out.println(map);

    // Since "D" is not present in map, so it will be set with value 1
    map.computeIfAbsent("D", function);
    System.out.println(map);
  }

}

Output :

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

Reference

https://docs.oracle.com/javase/8/docs/api/java/util/Map.html
 

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

One comment

  1. […] Java 8 Map : computeIfAbsent […]

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

%d bloggers like this: