.putIfAbsent()
Anonymous contributor
Published Jan 12, 2024
Contribute to Docs
The .putIfAbsent()
method in Java adds a key-value pair to a map if the key isn’t already there. If the key
exists, it returns its associated value
, showing no new addition. If the key
is not present, it adds the pair to the map and returns null
.
Syntax
map.putIfAbsent(key, value)
key
: It is thekey
to be inserted into the map.value
: It is thevalue
associated with thekey
.
Example
The following Java program demonstrates the .putIfAbsent()
method:
import java.util.*;public class Main {public static void main(String[] args) {// Creating a HashMapMap<Integer, String> map = new HashMap<>();// Adding some key-value pairsmap.put(1, "apple");map.put(2, "banana");map.put(3, null); // Adding a key with a null value// Using putIfAbsent methodString value1 = map.putIfAbsent(4, "orange");System.out.println("Value for key 4: " + value1);String value2 = map.putIfAbsent(2, "grape");System.out.println("Value for key 2: " + value2);String value3 = map.putIfAbsent(3, "pear");System.out.println("Value for key 3: " + value3);System.out.println("Updated Map: " + map);}}
The output of the above code is as follows:
Value for key 4: nullValue for key 2: bananaValue for key 3: nullUpdated Map: {1=apple, 2=banana, 3=pear, 4=orange}
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Java on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn Java
Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.Beginner Friendly16 hours