Java 8 Map : merge()

Map merge()

Syntax :


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

If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value.

Otherwise, replaces the associated value with the results of the given remapping function, or removes if the result is null. This method may be of use when combining multiple mapped values for a key.

package com.topjavatutorial;

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

public class TestMap4 {

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

    map.merge(1, 10, (x, y) -> x + y);
    // key 1 is present, so new value 10 will be added to previous value 1
    System.out.println(map); // {1=11, 2=2, 3=null}

    map.merge(2, 10, (x, y) -> x < y ? x : y);
    // Previous value for key=2 is less than new value. So, the old value
    // remains as per the BiFunction
    System.out.println(map); // {1=11, 2=2, 3=null}

    map.merge(3, 10, (x, y) -> x * y);
    // The old value for key=3 is null . But its not null * 3, the value 10
    // will be added for the key
    System.out.println(map); // {1=11, 2=2, 3=10}

    map.merge(4, 10, (x, y) -> x / y);
    // key=4 is not in map. So, BiFunction not evaluated, the element is
    // added to map
    System.out.println(map); // {1=11, 2=2, 3=10, 4=10}

    map.merge(1, 10, (x, y) -> null);
    // Since the BiFunction results in null, the element will be removed
    // from map
    System.out.println(map); // {2=2, 3=10, 4=10}

  }

}

Output :

{1=1, 2=2, 3=null}
{1=11, 2=2, 3=null}
{1=11, 2=2, 3=null}
{1=11, 2=2, 3=10}
{1=11, 2=2, 3=10, 4=10}
{2=2, 3=10, 4=10}
 

Reference

https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#merge-K-V-java.util.function.BiFunction-
 

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

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