Java 8 Map : 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);

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

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

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


Output :

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


© 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: