English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (Queue)

Java Map Collection

Java Set Collection

Java Input Output (I/O)

Java Reader/Writer

Java other topics

Java HashMap putIfAbsent() usage and example

Java HashMap Methods

If the specified key does not appear in the HashMap, the Java HashMap putIfAbsent() method will put the specified key/The value mapping is inserted into the HashMap.

The syntax of the putIfAbsent() method is:

hashmap.putIfAbsent(K key, V value)

putIfAbsent() parameters

The putIfAbsent() method has two parameters.

  • key - The specified value is mapped to key

  • value - Value associated with key

putIfAbsent() return value

  •  If the specified key already exists in the hash map, return the value associated with the key.

  • If the specified key does not exist in the hash map, return null

Note:If a null value was specified previously, return null value.

Example1:Java HashMap putIfAbsent()

import java.util.HashMap;
class Main {
  public static void main(String[] args){
    // Create HashMap
    HashMap<Integer, String> languages = new HashMap<>();
    // add mappings to HashMap
    languages.put(1, "Python");
    languages.put(2, "C");
    languages.put(3, "Java");
    System.out.println("Languages: ", + languages);
    //The key does not exist in the HashMap
    languages.putIfAbsent(4, "JavaScript");
    //The key appears in the HashMap
    languages.putIfAbsent(2, "Swift");
    System.out.println("Updated Languages: ", + languages);
  }
}

Output Result

Languages: {1=Python, 2=C, 3=Java}
Updated Languages: {1=Python, 2=C, 3=Java, 4=JavaScript}

In the above example, we created a hash map named languages. Note this line,

languages.putIfAbsent(4, "JavaScript");

Here, the key4Not associated with any value. Therefore, the putifAbsent() method will add the mapping {4 = JavaScript} added to the hash map.

Note this line,

languages.putIfAbsent(2, "Swift");

Here, the key2Already associated with Java. Therefore, the putIfAbsent() method will not add the mapping {2 = Swift} added to the hash map.

NoteWe have used the put() method to add a single mapping to the hash map. For more information, please visitJava HashMap put().

Java HashMap Methods