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

Java HashMap

Java HashMap

Java Collections Framework At this point, the trimToSize() method can remove the unallocated space and change the capacity of the ArrayList so that it equals the number of elements in the ArrayList.

HashMap is a hash table that stores key/value pair mappings.

HashMap implements the Map interface and stores data based on the HashCode value of the keys. It has fast access speed, allows at most one record with a null key, and does not support thread synchronization.

HashMap is unordered, meaning it does not record the order of insertion.

HashMap extends AbstractMap and implements the Map, Cloneable, and java.io.Serializable interfaces.

The key and value types of a HashMap can be the same or different; for example, both key and value can be of type String, or the key can be of type Integer and the value of type String.

The elements in a HashMap are actually objects; some common primitive types can use their wrapper classes.

can only be a reference data type, then we need to use the wrapper classes of the primitive types.

Basic types Reference type
boolean Boolean
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character

The HashMap class is in the java.util package and must be imported before use, as shown in the following syntax:

import java.util.HashMap; // 引入 HashMap 类

In the following example, we create a HashMap object Sites with an Integer key and a String value:

HashMap Sites = new HashMap();

Adding elements

The HashMap class provides many useful methods; to add a key/value pair, you can use the put() method:

Example

// Import the HashMap class      

import

java.util.HashMap

;

public

class

RunoobTest

{

   

public

static

void

main

(

String

[

]

args

)

{

       

// Create the HashMap object Sites

        HashMap

<

Integer

, String

Sites

=

new

HashMap

<

Integer

, String

(

)

;

       

// Add key/value pairs

        Sites.

put

(

1

,

"Google"

)

;

        Sites.

put

(

2

,

"Runoob"

)

;

        Sites.

put

(

3

,

"Taobao"

)

;

        Sites.

put

(

4

,

"Zhihu"

)

;

       

System

.

out

.

println

(

Sites

)

;

   

}

}

After executing the above code, the output is as follows:

{1=Google, 2=Runoob, 3=Taobao, 4=Zhihu}

The following example creates a key of type String and a value of type String:

Example

// Import the HashMap class      

import

java.util.HashMap

;

public

class

RunoobTest

{

   

public

static

void

main

(

String

[

]

args

)

{

       

// Create the HashMap object Sites

        HashMap

<

String

, String

Sites

=

new

HashMap

<

String

, String

(

)

;

       

// Add key/value pairs

        Sites.

put

(

"one"

,

"Google"

)

;

        Sites.

put

(

"two"

,

"Runoob"

)

;

        Sites.

put

(

"three"

,

"Taobao"

)

;

        Sites.

put

(

"four"

,

"Zhihu"

)

;

       

System

.

out

.

println

(

Sites

)

;

   

}

}

After executing the above code, the output is as follows:

{four=Zhihu, one=Google, two=Runoob, three=Taobao}

Accessing elements

We can use the get(key) method to retrieve the value corresponding to the key:

Example

// Import the HashMap class      

import

java.util.HashMap

;

public

class

RunoobTest

{

   

public

static

void

main

(

String

[

]

args

)

{

       

// Create the HashMap object Sites

        HashMap

<

Integer

, String

Sites

=

new

HashMap

<

Integer

, String

(

)

;

       

// Add key/value pairs

        Sites.

put

(

1

,

"Google"

)

;

        Sites.

put

(

2

,

"Runoob"

)

;

        Sites.

put

(

3

,

"Taobao"

)

;

        Sites.

put

(

4

,

"Zhihu"

)

;

       

System

.

out

.

println

(

Sites.

get

(

3

)

)

;

   

}

}

After executing the above code, the output is as follows:

Taobao

Delete elements

We can use the remove(key) method to delete the key/value pair corresponding to the key:

Example

// Import the HashMap class      

import

java.util.HashMap

;

public

class

RunoobTest

{

   

public

static

void

main

(

String

[

]

args

)

{

       

// Create the HashMap object Sites

        HashMap

<

Integer

, String

Sites

=

new

HashMap

<

Integer

, String

(

)

;

       

// Add key/value pairs

        Sites.

put

(

1

,

"Google"

)

;

        Sites.

put

(

2

,

"Runoob"

)

;

        Sites.

put

(

3

,

"Taobao"

)

;

        Sites.

put

(

4

,

"Zhihu"

)

;

        Sites.

remove

(

4

)

;

       

System

.

out

.

println

(

Sites

)

;

   

}

}

After executing the above code, the output is as follows:

{1=Google, 2=Runoob, 3=Taobao}

To remove all key/value pairs, you can use the clear method:

Example

// Import the HashMap class      

import

java.util.HashMap

;

public

class

RunoobTest

{

   

public

static

void

main

(

String

[

]

args

)

{

       

// Create the HashMap object Sites

        HashMap

<

Integer

, String

Sites

=

new

HashMap

<

Integer

, String

(

)

;

       

// Add key/value pairs

        Sites.

put

(

1

,

"Google"

)

;

        Sites.

put

(

2

,

"Runoob"

)

;

        Sites.

put

(

3

,

"Taobao"

)

;

        Sites.

put

(

4

,

"Zhihu"

)

;

        Sites.

clear

(

)

;

       

System

.

out

.

println

(

Sites

)

;

   

}

}

After executing the above code, the output is as follows:

{}

// Delete the fourth element

To count the number of elements in a HashMap, you can use the size() method:

Example

// Import the HashMap class      

import

java.util.HashMap

;

public

class

RunoobTest

{

   

public

static

void

main

(

String

[

]

args

)

{

       

// Create the HashMap object Sites

        HashMap

<

Integer

, String

Sites

=

new

HashMap

<

Integer

, String

(

)

;

       

// Add key/value pairs

        Sites.

put

(

1

,

"Google"

)

;

        Sites.

put

(

2

,

"Runoob"

)

;

        Sites.

put

(

3

,

"Taobao"

)

;

        Sites.

put

(

4

,

"Zhihu"

)

;

       

System

.

out

.

println

(

Sites.

size

(

)

)

;

   

}

}

After executing the above code, the output is as follows:

4

Iterating Over a HashMap

You can use for-each to iterate over the elements in a HashMap.

If you only want to get the keys, you can use the keySet() method and then use get(key) to obtain the corresponding value; if you only want to get the values, you can use the values() method.

Example

// Import the HashMap class      

import

java.util.HashMap

;

public

class

RunoobTest

{

   

public

static

void

main

(

String

[

]

args

)

{

       

// Create the HashMap object Sites

        HashMap

<

Integer

, String

Sites

=

new

HashMap

<

Integer

, String

(

)

;

       

// Add key/value pairs

        Sites.

put

(

1

,

"Google"

)

;

        Sites.

put

(

2

,

"Runoob"

)

;

        Sites.

put

(

3

,

"Taobao"

)

;

        Sites.

put

(

4

,

"Zhihu"

)

;

       

// Output key and value

       

for

(

Integer

i

:

Sites.

keySet

(

)

)

{

           

System

.

out

.

println

(

"key: "

i

" value: "

Sites.

get

(

i

)

)

;

       

}

       

// Return all values

       

for

(

String

value

:

Sites.

values

(

)

)

{

         

// Output each value

         

System

.

out

.

print

(

value

", "

)

;

       

}

   

}

}

After executing the above code, the output is as follows:


key: 1 value: Google
key: 2 value: Runoob
key: 3 value: Taobao
key: 4 value: Zhihu
Google, Runoob, Taobao, Zhihu,

Java HashMap Methods

hashmap

The commonly used methods of Java HashMap are listed below:

Method Description
clear() Remove all key/value pairs from the HashMap
clone() Copy a HashMap
isEmpty() Check whether the HashMap is empty
size() Count the number of key/value pairs in the HashMap
put() Add a key/value pair to the HashMap
putAll() Add all key/value pairs to the HashMap
putIfAbsent() If the specified key does not exist in the HashMap, insert the specified key/value pair into the HashMap.
remove() Remove the mapping for the specified key from the HashMap
containsKey() Check whether the mapping for the specified key exists in the HashMap.
containsValue() Check whether the mapping for the specified value exists in the HashMap.
replace() Replace the value corresponding to the specified key in the HashMap.
replaceAll() Replace all mappings in the HashMap with the results produced by the given function.
get() Get the value corresponding to the specified key
getOrDefault() Get the value corresponding to the specified key; if the key is not found, return the set default value
forEach() Perform the specified action on each mapping in the HashMap.
entrySet() Return a Set view of all mappings in the HashMap.
keySet() Return a Set view of all keys in the HashMap.
values() Return all value values existing in the HashMap.
merge() Add a key/value pair to the HashMap
compute() Recalculate the value of the specified key in the HashMap
computeIfAbsent() Recalculate the value of the specified key in the HashMap, and add it to the HashMap if this key does not exist
computeIfPresent() Recalculate the value of the specified key in the HashMap, provided that the key exists in the HashMap.

Traverse every element in the arraylist and perform a specific operationhttps://www.runoob.com/manual/jdk11api/java.base/java/util/HashMap.html

Java Collections Framework At this point, the trimToSize() method can remove the unallocated space and change the capacity of the ArrayList so that it equals the number of elements in the ArrayList.