Close

Java Collections - Only put Map key/value if the specified key does not exist

[Last Updated: Apr 17, 2020]

Java Collections Java 

Following example shows how to put a java.util.Map entry only if the related key doesn't already exist in the Map.

The method Map#put() overrides the existing key/value, whereas, the method Map#putIfAbsent() only overrides if the key does not exist in the map

package com.logicbig.example;

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

public class MapPutOnlyIfNotExists {

  public static void main(String[] args) {
      Map<String, Integer> personSalaryMap= new HashMap<>();
      personSalaryMap.put("John", 2000);
      personSalaryMap.put("Tina", 3000);
      personSalaryMap.put("Jenny", 5000);
      System.out.println("-- original --");
      System.out.println(personSalaryMap);

      //put only if key does not exists
      personSalaryMap.putIfAbsent("Tina", 7000);
      System.out.println("-- After map#putIfAbsent() --");
      System.out.println(personSalaryMap);

      //put even if key exists i.e. replace the entry
      personSalaryMap.put("Tina", 7000);
      System.out.println("-- After map#put() --");
      System.out.println(personSalaryMap);
  }
}
-- original --
{John=2000, Jenny=5000, Tina=3000}
-- After map#putIfAbsent() --
{John=2000, Jenny=5000, Tina=3000}
-- After map#put() --
{John=2000, Jenny=5000, Tina=7000}

See Also