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

getOrDefault()

Example

Print the value of an entry in a map, or “Unknown” if the entry does not exist.

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");
   System.out.println(capitalCities.getOrDefault("England", "Unknown"));
   System.out.println(capitalCities.getOrDefault("Canada", "Unknown"));
  }
}

Definition and Usage

The getOrDefault() method returns the value of the entry in the map with the specified key. If the entry does not exist, it returns the value of the second parameter.

Syntax

public V get(Object key, V def)

V represents the data type of the values stored in the map.

Parameter Values

Parameter

Description

key

Required: Specifies the key of the entry from which to retrieve the value.

def

Required: Specifies the default value to be returned if an entry is not found.

Technical Details

Returns:

It returns the value of the entry with the specified key, or the value of the default argument if there is no entry with that key.