Monday, October 17, 2022

Java Map putIfAbsent() With Examples

The putIfAbsent() method in java.util.Map is added in Java 8 and it puts a new value for the specified key only if the specified key is not already associated with a value in the Map or is mapped to null. There is also a computeIfAbsent() method in Java which also puts a value if specified key is not already associated with a value but with computeIfAbsent() value is computed using the given mapping function.

Syntax of the putIfAbsent () method is as given below.

V putIfAbsent(K key, V value)

Parameters are as-

  • key- key with which the specified value is to be associated
  • value- value to be associated with the specified key

Method returns the previous value if the specified key is already associated with the value.

Returns null if specified key is not already present in the Map, which actually means key is absent and the method is inserting the given key, value pair in the Map. It may also mean that the key is present but associated with null value.

The default implementation for putIfAbsent() is as given below. As you can see just by using single method putIfAbsent() you get the logic of checking whether the key is already present or not in the map and putting the value in case key is not there (or associated value is null).

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

putIfAbsent () Java examples

1. In the first example we'll have a map of cities and we'll try to insert a new city with a key which already exists in the HashMap.

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

public class PutIfAbsentDemo {

  public static void main(String[] args) {
    // Setting up a HashMap
    Map<String, String> cityMap = new HashMap<String, String>();
    cityMap.put("1","New York City" );
    cityMap.put("2", "New Delhi");
    cityMap.put("3", "Mumbai");
    cityMap.put("4", "Berlin");
    String val = cityMap.putIfAbsent("4", "London");
    System.out.println("Value is- " + val);   
    System.out.println(cityMap);
  }
}

Output

Value is- Berlin
{1=New York City, 2=New Delhi, 3=Mumbai, 4=Berlin}

Since key already exists and mapped with a value in the HashMap so putIfAbsent() method won't replace the previous value with new value for the same key. Also notice the return value of the method which is the value associated with the specified key.

2. In this example we'll try to insert a new city with a key which is not already there in the Map.

public class PutIfAbsentDemo {

  public static void main(String[] args) {
    // Setting up a HashMap
    Map<String, String> cityMap = new HashMap<String, String>();
    cityMap.put("1","New York City" );
    cityMap.put("2", "New Delhi");
    cityMap.put("3", "Mumbai");
    cityMap.put("4", "Berlin");
    String val = cityMap.putIfAbsent("5", "London");
    System.out.println("Value is- " + val);   
    System.out.println(cityMap);
  }
}

Output

Value is- null
{1=New York City, 2=New Delhi, 3=Mumbai, 4=Berlin, 5=London}

Since key is not there in the Map so a new entry is added to the HashMap. Also notice the return value of the putifAbsent() method which is null this time because there was no mapping for the key.

3. In this example we'll take the scenario when the key exists in the HashMap but mapped with null.

public class PutIfAbsentDemo {

  public static void main(String[] args) {
    // Setting up a HashMap
    Map<String, String> cityMap = new HashMap<String, String>();
    cityMap.put("1","New York City" );
    cityMap.put("2", "New Delhi");
    cityMap.put("3", "Mumbai");
    cityMap.put("4", null);
    String val = cityMap.putIfAbsent("4", "London");
    System.out.println("Value is- " + val);   
    System.out.println(cityMap);
  }
}

Output

Value is- null
{1=New York City, 2=New Delhi, 3=Mumbai, 4=London}

Since the key is mapped to null so putIfAbsent() method associates the key with a new value.

That's all for this topic Java Map putIfAbsent() With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Java Map merge() With Examples
  2. Java Map getOrDefault() Method With Examples
  3. Map.Entry Interface in Java
  4. EnumSet in Java With Examples
  5. Java Collections Interview Questions And Answers

You may also like-

  1. Java StampedLock With Examples
  2. CopyOnWriteArraySet in Java With Examples
  3. Garbage Collection in Java
  4. Difference Between Checked And Unchecked Exceptions in Java
  5. How to Read Excel File in Java Using Apache POI
  6. Spring Boot StandAlone (Console Based) Application Example
  7. Spring MVC Exception Handling - @ExceptionHandler And @ControllerAdvice Example
  8. Angular @HostBinding Decorator With Examples

No comments:

Post a Comment