Skip to content

Yet another programming solutions log

Sample bits from programming for the future generations.

Technologies Technologies
  • Algorithms and Data Structures
  • Java Tutorials
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Spock Framework Tutorial
  • Spring Framework
  • Bash Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Developer’s Tools
  • Productivity
  • About
Expand Search Form

Java Util Map merge(key, value, BiFunction)

farenda 2016-06-17 0

java.util.Map.merge(key, value, BiFunction)

The method Map.merge(key, value, BiFunction) associates given value with the given key or calculates the new value from the old value and the given one using provided remapping function.

Method signature

The signature of the java.util.Map.merge(key, value, BiFunction) method is as follows:

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

The method is available since Java 8.

Parameters

  • K key: the key with which to associate the result
  • V value: non-null value to merge with existing value or to be used as the new value if there is no current mapping or the mapping is null
  • BiFunction remappingFunction: a two argument function to be used for calculation of the new mapping from the old value and given value.

Return value

The new value associated with the given key or null if there is no mapping.

Exceptions

  • UnsupportedOperationException: when the put operation is not supported by this map (optional)
  • ClassCastException: if the class of key or value prevents it from storing in the map (optional)
  • NullPointerException: if the specified key is null and this map does not permit null keys or remappingFunction is null.

Example usage

In the following code we use java.util.Map.merge(key, value, BiFunction) to update total prices of products. We use Integer.sum(a,b) as our BiFunction (two-argument function):

package com.farenda.java.util;

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

public class MapExamples {

    public static void main(String[] args) {
        Map<String, Integer> prices = new HashMap<>();
        System.out.println("Prices map: " + prices);

        // Integer::sum(a,b) is perfect two-argument
        // function (BiFunction)
        prices.merge("fruits", 3, Integer::sum);
        prices.merge("fruits", 5, Integer::sum);
        System.out.println("Prices map: " + prices);

        // null removes mapping for the key:
        prices.merge("fruits", 7, (oldVal, newVal) -> {
            System.out.printf("Old val: %d, new val: %d%n",
                    oldVal, newVal);
            return null;
        });
        System.out.println("Prices map: " + prices);

        prices.put("veggies", null);
        System.out.println("Prices map: " + prices);
        // No need to handle initial null value:
        prices.merge("veggies", 42, Integer::sum);
        System.out.println("Prices map: " + prices);
    }
}

The above code produces the following output:

Prices map: {}
Prices map: {fruits=8}
Old val: 8, new val: 7
Prices map: {}

In the following example we’re going to show a nice feature of Map.merge(key,value,BiFunction), namely that we don’t have have to worry about initial null value in our BiFunction, because when the mapping’s value is null, then the new value is used immediately, without call to the BiFunction:

package com.farenda.java.util;

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

public class MapExamples {

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

        prices.put("veggies", null);
        System.out.println("Prices map: " + prices);

        // No need to handle initial null value:
        prices.merge("veggies", 42, Integer::sum);
        System.out.println("Prices map: " + prices);
    }
}

The above code produces the following output:

Prices map: {veggies=null}
Prices map: {veggies=42}

References:

  • Java 8 Map API
Share with the World!
Categories Java Tags java, java-collections, java-util, java8
Previous: Java Util Map getOrDefault
Next: Java Lang Tutorial

Recent Posts

  • Java 8 Date Time concepts
  • Maven dependency to local JAR
  • Caesar cipher in Java
  • Java casting trick
  • Java 8 flatMap practical example
  • Linked List – remove element
  • Linked List – insert element at position
  • Linked List add element at the end
  • Create Java Streams
  • Floyd Cycle detection in Java

Pages

  • About Farenda
  • Algorithms and Data Structures
  • Bash Tutorial
  • Bean Validation Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Java 8 Streams and Lambda Expressions Tutorial
  • Java Basics Tutorial
  • Java Collections Tutorial
  • Java Concurrency Tutorial
  • Java IO Tutorial
  • Java Tutorials
  • Java Util Tutorial
  • Java XML Tutorial
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Software Developer’s Tools
  • Spock Framework Tutorial
  • Spring Framework

Tags

algorithms bash bean-validation books clojure design-patterns embedmongo exercises git gof gradle groovy hateoas hsqldb i18n java java-basics java-collections java-concurrency java-io java-lang java-time java-util java-xml java8 java8-files junit linux lists log4j logging maven mongodb performance quartz refactoring regex rest slf4j solid spring spring-boot spring-core sql unit-tests

Yet another programming solutions log © 2022

sponsored
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.Ok