Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java HashMap getOrDefault() Method

Java HashMap getOrDefault() Method

Java HashMap Java HashMap

The getOrDefault() method retrieves the value corresponding to the specified key; if the key is not found, it returns the set default value.

The syntax of the getOrDefault() method is:


hashmap.getOrDefault(Object key, V defaultValue)

**Note:** hashmap is an object of the HashMap class.

Parameter Description:

Return Value

Returns the value mapped to the key, or the specified default value if the given key is not found in the mapping.

Example

The following example demonstrates the use of the getOrDefault() method:

Example

import

java.util.HashMap

;

class

Main

{

   

public

static

void

main

(

String

[

]

args

)

{

       

// Create a HashMap

        HashMap

<

Integer

, String

sites

=

new

HashMap

<>

(

)

;

       

// Add some elements to the HashMap

        sites.

put

(

1

,

"Google"

)

;

        sites.

put

(

2

,

"Runoob"

)

;

        sites.

put

(

3

,

"Taobao"

)

;

       

System

.

out

.

println

(

"sites HashMap: "

sites

)

;

       

// The mapping for the key exists in the HashMap

       

// Not Found - if the HashMap does not contain this key, the default value is returned

       

String

value1

=

sites.

getOrDefault

(

1

,

"Not Found"

)

;

       

System

.

out

.

println

(

"Value for key 1:  "

value1

)

;

       

// The mapping for the key does not exist in the HashMap

       

// Not Found - if the HashMap does not contain this key, the default value is returned

       

String

value2

=

sites.

getOrDefault

(

4

,

"Not Found"

)

;

       

System

.

out

.

println

(

"Value for key 4: "

value2

)

;

   

}

}

The output of the above program is:


Value for key 1:  Google
Value for key 4: Not Found

**Note:** We can use HashMap containsKey() Methodto check whether a specific key exists in the HashMap.

Java HashMap Java HashMap