Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

putIfAbsent()

Example

Insert entries into a map.

import java.util.HashMap;
public class Main {
  public static void main(String[] args) {
    HashMap<String, String> capitalCities = new HashMap<String, String>();
    capitalCities.put("England", "London");
    capitalCities.put("Germany", "Berlin");
    capitalCities.put("Norway", "Oslo");
    capitalCities.put("USA", "Washington DC");             
    // Add new entries only if they don't exist
    capitalCities.putIfAbsent("Canada", "Ottawa");
    capitalCities.putIfAbsent("England", "Cambridge");
    System.out.println(capitalCities);
 }
}

Definition and Usage

The putIfAbsent() method inserts an entry into the map. If an entry with the same key already exists and its value is not null, the map remains unchanged.

Syntax

public V putIfAbsent(K key, V value)

K and V represent the data types of the keys and values in the map.

Parameter Values

Parameter

Description

key

Required: Specifies the key for the map entry.

value

Required: Specifies the value for the map entry.

Technical Details

Returns:

If an entry exists with the specified key, it returns the value of that entry; otherwise, it returns null.