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

Java HashMap containsKey() Method

Java HashMap containsKey() Method

Java HashMap Java HashMap

The containsKey() method checks whether the mapping corresponding to the specified key exists in the HashMap.

The syntax of the containsKey() method is:


hashmap.containsKey(Object key)

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

Parameter Description:

Return Value

Returns true if the mapping corresponding to the specified key exists in the HashMap, otherwise returns false.

Example

The following example demonstrates the use of the containsKey() 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

)

;

       

// Check whether key 1 exists

       

if

(

sites.

containsKey

(

1

)

)

{

           

System

.

out

.

println

(

"key 1 exists in sites"

)

;

       

}

   

}

}

The output of the above program is:


sites HashMap: {1=Google, 2=Runoob, 3=Taobao}
key 为 1 存在于 sites 中

For non-existent keys, we can perform an insertion.

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

)

;

       

// Check whether key 4 exists; if not, insert this key/value pair

       

// Use the ! symbol to negate the boolean result

       

if

(

!

sites.

containsKey

(

4

)

)

{

            sites.

put

(

4

,

"Wiki"

)

;

       

}

       

System

.

out

.

println

(

"Updated sites HashMap: "

sites

)

;

   

}

}

The output of the above program is:


sites HashMap: {1=Google, 2=Runoob, 3=Taobao}
Updated sites HashMap: {1=Google, 2=Runoob, 3=Taobao, 4=Wiki}

**Note:** We can also use HashMap putIfAbsent() Methodperforms the same operation.

Java HashMap Java HashMap