What is the difference between putIfAbsent and computeIfAbsent in Java 8 Map?

Reading interesting articles, guys argue that the difference between two functions:

Both functions seek to add an element if the specified key is not already present on the card.

putIfAbsent adds an element with the specified value, while computeIfAbsent adds an element with the value calculated using the key. http://www.buggybread.com/2014/10/java-8-difference-between-map.html

AND

We have seen that putIfAbsent eliminates the imperative way of having an if-statement defined, but what if fetching Java articles really hurts our work?

To optimize this, we do not want to receive articles until we are really sure that we need them - this means that we need to know whether the key is missing before learning the articles. http://www.deadcoderising.com/2017-02-14-java-8-declarative-ways-of-modifying-a-map-using-compute-merge-and-replace/

I was not ready to understand what are the differences, can you talk more about these two functions?

+48
source share
7 answers

Difference # 1

computeIfAbsent takes a matching function, which is called to get the value if the key is missing.

putIfAbsent takes value directly.

If the value is expensive to get, then it putIfAbsentdestroys it if the key already exists.

"" , , new ArrayList<>(), Map<K, List<V>>, , ( ), .


# 2

computeIfAbsent " ( ) , , null, null".

putIfAbsent " , , null, ".

, , , , computeIfAbsent , putIfAbsent null.


№ 3

"", null, :

computeIfAbsent , .

putIfAbsent , , null.

computeIfAbsent, putIfAbsent get, getOrDefault containsKey.

+88

, Map<String,ValueClass>.

map.putIfAbsent("key", new ValueClass());

ValueClass , "" Map. .

,

map.computeIfAbsent("key", k -> new ValueClass());

ValueClass, "" Map ( null).

computeIfAbsent .

putIfAbsent :

ValueClass value = new ValueClass();
if (map.get("key") == null) {
    map.put("key",value);
}

computeIfAbsent :

if (map.get("key") == null) {
    map.put("key",new ValueClass());
}

, computeIfAbsent null . putIfAbsent .

+44

, :

  • putIfAbsent , .
  • computeIfAbsent Function. , , .

, putIfAbsent.

, - (, ), computeIfAbsent, , .

+3

, ....

default V putIfAbsent​(K key, V value) , :

 V v = map.get(key);
  if (v == null)
      v = map.put(key, value);
  return v;

:

default V computeIfAbsent​(K key,
                          Function<? super K,? extends V> mappingFunction)

:

if (map.get(key) == null) {
     V newValue = mappingFunction.apply(key);
     if (newValue != null)
         map.put(key, newValue);
}
+2

V putIfAbsent(K key, V value) - ( ), , null.

V computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction) - ( ), , null.

. https://docs.oracle.com/javase/8/docs/api/java/util/Map.html

+1

. , (" , computeIfAbsent") . , :

putIfAbsent() put(), map . putIfAbsent() , . , , .

computeIfAbsent() , . , , newValue . , .

Refer to the following program for reference:

public class MapTest1 {
    public static final String AJAY_DEVGAN = "Ajay Devgn";
    public static final String AUTOBIOGRAPHY = "Autobiography";

    public static void main(String[] args) {
        MapTest1 mt = new MapTest1();
        mt.testPutCompute();
    }

    private void testPutCompute() {
        Map<String, List<String>> movies = getMovieObject();
        System.out.println("\nCalling putIfAbsent method.....");
        //System.out.println(movies.get(AJAY_DEVGAN));
        //movies.put(AJAY_DEVGAN, getAjayDevgnMovies());
        movies.putIfAbsent(AJAY_DEVGAN, getAjayDevgnMovies());

        System.out.println("\nCalling computeIfAbsent method......");
        //System.out.println(movies.get(AUTOBIOGRAPHY));
        movies.computeIfAbsent(AUTOBIOGRAPHY, t -> getAutobiographyMovies());

    }

    private Map<String, List<String>> getMovieObject() {
        Map<String, List<String>> movies = new HashMap<>();     

        movies.put(AJAY_DEVGAN, getAjayDevgnMovies());
        movies.put(AUTOBIOGRAPHY, getAutobiographyMovies());

        System.out.println(movies);
        return movies;
    }

    private List<String> getAutobiographyMovies() {
        System.out.println("Getting autobiography movies");
        List<String> list = new ArrayList<>();
        list.add("M.S. Dhoni - The Untold Story");
        list.add("Sachin: A Billion Dreams");
        return list;
    }

    private List<String> getAjayDevgnMovies() {
        System.out.println("Getting Ajay Devgn Movies");
        List<String> ajayDevgnMovies = new ArrayList<>();
        ajayDevgnMovies.add("Jigar");
        ajayDevgnMovies.add("Pyar To Hona Hi Tha");
        return ajayDevgnMovies;
    }
}

See the following code for putIfAbsent () and computeIfAbsent () from the Map.class interface

public interface Map<K,V> {
.....

 default V putIfAbsent(K key, V value) {
        V v = get(key);
        if (v == null) {
            v = put(key, value);
        }

        return v;
    }

 default V computeIfAbsent(K key,
            Function<? super K, ? extends V> mappingFunction) {
        Objects.requireNonNull(mappingFunction);
        V v;
        if ((v = get(key)) == null) {
            V newValue;
            if ((newValue = mappingFunction.apply(key)) != null) {
                put(key, newValue);
                return newValue;
            }
        }

        return v;
    }   
.........
}
0
source
Take this simple Example for putIfAbsent():
Map myMap = new HashMap();
myMap.put(1,"ABC");
myMap.put(2,"XYZ");
myMap.put(3,"GHI");
//Output of map till this point is : 1-> "ABC", 2-> "XYZ", 3-> "GHI"
myMap.putIfAbsent(3,"cx");
//Output of map till this point is : 1-> "ABC", 2-> "XYZ", 3-> "GHI"
cx will be value of 3 if there is no Value of 3 in the map already.
-1
source

All Articles