Java HashMap putIfAbsent() method example

HQ ┬╗ Java Tutorial ┬╗ java.util ┬╗ Hashmap ┬╗ putIfAbsent() method example
Java HashMap putIfAbsent() method example 2018-02-16T07:27:12+00:00

java.util.HashMap putIfAbsent()

Description

On this document we will be showing a java example on how to use the putIfAbsent() method of HashMap Class. Basically this method is being used to insert a new a new key-value mapping to the hashmap object if the respective id is not yet used. A value null will be returned if the key-value mapping is successfully added to the hashmap object while if the id is already present on the hashmap the value which is already existing will returned instead.

In dealing with HashMap methods, as a general rule you must always watch out for Generics such that if we have declared our map like HashMap<Integer,String> map = new HashMap<Integer,String>();  then the returned keys are expected to be Integer object type or its subclass and the values as String.

Important notes for putIfAbsent() method:

  • ┬áspecified by putIfAbsent in interface Map<K,V>

Method Syntax

public V putIfAbsent(K key, V value)

Method Argument

Data Type Parameter Description
K key key with which the specified value is to be associated
V value value to be associated with the specified key

Method Returns

The putIfAbsent() method returns the previous value associated with the specified key, or null if there was no mapping for the key. (A null return can also indicate that the map previously associated null with the key, if the implementation supports null values.)

Compatibility

Requires Java 1.2 and up

Java HashMap putIfAbsent(K key, V value) Example

Below is a java code demonstrates the use of putIfAbsent() method of HashMap class. The example presented might be simple however it shows the behavior of the putIfAbsent() method.

This example is a lot simpler than it looks. First we have a method init() which generally populates a HashMap object and returned. This method has been called by the main method and then we have tried inserting a new value to the key-value pair mapping by using the putIfAbsent() method. To test the returned value we have introduced a code block to check if the returned string is null which means a successful  insertion/addition of value, otherwise we print the existing student which currently uses the student id we are trying to add.

Sample Output

Below is the sample output when you run the above example.

HashHamp putIfAbsent() method example

Contact Info

Singapore

Our Goal

JavaTutorialHQ aims to to be The Ultimate Guide on Java with hundreds of examples from basic to advance Topics.

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close