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

Java HashMap keySet() Method

Java HashMap keySet() Method

Java HashMap Java HashMap

The keySet() method returns a Set view of all keys in the map.

The syntax of the keySet() method is:


hashmap.keySet()

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

Parameter Description:

Return Value

Returns a Set view of all keys in the map.

Example

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

)

;

       

// Return the set view consisting of all keys

       

System

.

out

.

println

(

"Keys: "

sites.

keySet

(

)

)

;

   

}

}

The output of the above program is:


sites HashMap: {1=Google, 2=Runoob, 3=Taobao}
Keys: [1, 2, 3]

The keySet() method can be used with a for-each loop to iterate over all keys in the HashMap.

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

)

;

       

// Return the set view consisting of all keys

       

System

.

out

.

println

(

"Keys: "

sites.

keySet

(

)

)

;

       

// keySet() returns a set view of all keys

       

// for-each loop accesses each key in this view

       

for

(

int

key

:

sites.

keySet

(

)

)

{

         

// Output each key

           

System

.

out

.

print

(

key

", "

)

;

       

}

   

}

}

The output of the above program is:

sites HashMap: {1=Google, 2=Runoob, 3=Taobao}
Keys: [1, 2, 3]
1, 2, 3, 

Java HashMap Java HashMap