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

Java HashMap size() Method

Java HashMap size() Method

Java HashMap Java HashMap

The size() method is used to count the number of key/value pairs in the HashMap.

The size() method is used to return the number of elements in the dynamic array.


hashmap.size()

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

Parameter Description:

Return Value

Returns the number of key/value pairs in the HashMap.

Example

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

Example

import

java.util.HashMap

;

class

Main

{

   

public

static

void

main

(

String

[

]

args

)

{

        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

(

"HashMap: "

sites

)

;

       

// Get the number of key/value pair mappings in this HashMap

       

int

size

=

sites.

size

(

)

;

       

System

.

out

.

println

(

"Size of HashMap: "

size

)

;

   

}

}

The output of the above program is:


HashMap: {1=Google, 2=Runoob, 3=Taobao}
Size of HashMap: 3

In the above example, we created a HashMap named sites, and then used the size() method to count the number of key/value pairs in sites.

Java HashMap Java HashMap