Compute

Most of the time, a value from a map needs to be updated, the traditional way is to get the value from the map if the value is present then update the value and put it back on to map.

package org.wesome.java8;

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

class Apple {
    public static void main(String[] args) {

        Map<Integer, String> map = new HashMap<>();
        map.put(1, "Macintosh");
        map.put(2, "Fuji");
        map.put(3, "Gala");
        map.put(4, "Jonagold");

        String temp = map.get(1);
        if (Objects.nonNull(temp) && temp.equals("Macintosh")) {
            map.put(1, "MACINTOSH");
        }

        System.out.println("map = " + map);
    }
}

to avoid the boilerplate if condition, Java 8 introduced the compute method in Map Interface, it internally checks the key should be present on the map and updates the value corresponding to the key.

compute method will modify the single entity Map

The compute method will be available for all Map Intertface implementing concrete classes such as HashMapLinkedHashMap and TreeMap ect

package org.wesome.java8;

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

class Apple {
    public static void main(String[] args) {
        BiFunction<Integer, String, String> biFunction = (key, value) -> value + " Apple";

        Map<Integer, String> map = new HashMap<>();
        map.put(1, "Macintosh");
        map.put(2, "Fuji");
        map.put(3, "Gala");
        map.put(4, "Jonagold");

        /*  compute the entry with the new value using lambda expression    */
        map.compute(1, (k, v) -> v.concat(" Apple"));

        /*  compute the entry with the new value using BiFunction  */
        map.compute(2, biFunction);

        System.out.println("map = " + map);
    }
}

follow us on