Wednesday, 20 July 2022

Java: Map merge method demo

Signature

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.

 

Example

 

pricesMap.merge("rms", 10.0, (oldValue, newValue) -> oldValue - newValue);

 

Above snippet reduce the price of the product 'rms' by 10 if the key rms exists in the map, else add new entry with the key ‘rms’ and the value ‘10.0’

 

Default implementation of merge method looks like below.

 

V merge(K key, V value,
        BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
    Objects.requireNonNull(remappingFunction);
    Objects.requireNonNull(value);
    V oldValue = get(key);
    V newValue = (oldValue == null) ? value :
               remappingFunction.apply(oldValue, value);
    if(newValue == null) {
        remove(key);
    } else {
        put(key, newValue);
    }
    return newValue;
}

 

Find the below working application.

 


MapMergeDemo.java

 

package com.sample.app.collections;

import java.util.HashMap;
import java.util.Map;

public class MapMergeDemo {

    public static void main(String[] args) {
        Map<String, Double> pricesMap = new HashMap<>();

        pricesMap.put("dlpt", 25000.23);
        pricesMap.put("rms", 500.88);
        pricesMap.put("sgs", 47.89);

        System.out.println(pricesMap);

        System.out.println("\nLet's reduce the price of the product rms by 10 using merge function\n");

        pricesMap.merge("rms", 10.0, (oldValue, newValue) -> oldValue - newValue);

        System.out.println(pricesMap);
        
        System.out.println("\nLet's add new entry using merge function\n");
        
        pricesMap.merge("tshts", 45.3, (oldValue, newValue) -> oldValue - newValue);

        System.out.println(pricesMap);
    }
}

 

Output

{dlpt=25000.23, rms=500.88, sgs=47.89}

Let's reduce the price of the product rms by 10 using merge function

{dlpt=25000.23, rms=490.88, sgs=47.89}

Let's add new entry using merge function

{tshts=45.3, dlpt=25000.23, rms=490.88, sgs=47.89}

 

 

 

 

 

Previous                                                 Next                                                 Home

No comments:

Post a Comment