Java HashMap example

HashMap is an object that stores both key=value as a pair. This HashMap permits null values and the null key, unsynchronized and no guarantees to the order of the map.


["key","value"] = ["java","mkyong.com"]

1. HashMap Basic

1.1 Add an Item


	Map map = new HashMap<String, String>();
	map.put("PostgreSQL", "Free Open Source Enterprise Database");

1.2 Get an Item


	map.get("PostgreSQL"); // output : Free Open Source Enterprise Database

1.3 Update an Item


	map.put("PostgreSQL", "Still the best!");
	map.get("PostgreSQL"); // output : Still the best!

	// @Since 1.8
	map.replace("PostgreSQL", "Still the best! 2");
	map.get("PostgreSQL"); // output : Still the best! 2

1.4 Remove an Item


	map.remove("PostgreSQL");
	map.get("PostgreSQL"); // output : null

1.5 Remove everything


	map.clear();

1.6 Get Size


	map.size();

2. Loop HashMap

There are 3 ways to loop or iterate a HashMap

2.1 If possible, always uses Java 8 forEach, simple and nice.


	Map<String, String> map = new HashMap<>();
    map.forEach((key, value) -> System.out.println("[Key] : " + key + " [Value] : " + value));

2.2 Normal for loop.


	Map<String, String> map = new HashMap<>();
	
	for (Map.Entry<String, String> entry : map.entrySet()) {
		System.out.println("[Key] : " + entry.getKey() + " [Value] : " + entry.getValue());
	}

2.3 Iterator, classic.


	Map<String, String> map = new HashMap<>();
       
	Iterator iter = map.entrySet().iterator();
	while (iter.hasNext()) {
		Map.Entry entry = (Map.Entry) iter.next();
		System.out.println("[Key] : " + entry.getKey() + " [Value] : " + entry.getValue());
	}

3. Collections.synchronizedMap

3.1 This HashMap is unsynchronized, if multiple threads access a HashMap concurrently, it will mess up the values. To use HashMap in a multiple thread’s environment, try Collections.synchronizedMap(new HashMap<>()) to create a synchronized map.

HashMapSynchronized.java

package com.mkyong;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class HashMapSynchronized {

    public static void main(String[] args) {

		// this map is synchronized
        Map<String, Integer> map = Collections.synchronizedMap(new HashMap<>());
		
        map.put("web", 1024);
        map.put("backend", 2048);

        map.forEach((key, value) -> System.out.println("[Key] : " + key + " [Value] : " + value));

    }

}

4. HashMap

A full example, just for reference.

HashMapExample.java

package com.mkyong;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class HashMapExample {

    public static void main(String[] args) {

        Map<String, String> map = new HashMap<>();
        map.put("PostgreSQL", "Free Open Source Enterprise Database");
        map.put("DB2", "Enterprise Database , It's expensive");
        map.put("Oracle", "Enterprise Database , It's expensive");
        map.put("MySQL", "Free Open SourceDatabase (no more, try MariaDB)");

        // Get
        System.out.println(map.get("PostgreSQL")); // Free Open Source Enterprise Database

        // Update
        map.put("PostgreSQL", "Still the best!");
        System.out.println(map.get("PostgreSQL")); // Still the best!

        // @Since 1.8
        map.replace("PostgreSQL", "Still the best! 2");
        System.out.println(map.get("PostgreSQL")); // Still the best! 2

        // Remove
        map.remove("PostgreSQL");
        System.out.println(map.get("PostgreSQL")); // null

        // Size
        System.out.println(map.size()); // 3

        // loop
        System.out.println("Iterator loop...");
        Iterator iter = map.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            System.out.println("[Key] : " + entry.getKey() + " [Value] : " + entry.getValue());
        }

        System.out.println("for loop...");
        for (Map.Entry<String, String> entry : map.entrySet()) {
            System.out.println("[Key] : " + entry.getKey() + " [Value] : " + entry.getValue());
        }

        // Java 8
        System.out.println("forEach loop...");
        map.forEach((key, value) -> System.out.println("[Key] : " + key + " [Value] : " + value));

        // clear everything
        map.clear();

		// nothing
        map.forEach((key, value) -> System.out.println("[Key] : " + key + " [Value] : " + value));

    }

}

Output


Free Open Source Enterprise Database
Still the best!
Still the best! 2
null
3
Iterator loop...
[Key] : DB2 [Value] : Enterprise Database , It's expensive
[Key] : MySQL [Value] : Free Open SourceDatabase (no more, try MariaDB)
[Key] : Oracle [Value] : Enterprise Database , It's expensive
for loop...
[Key] : DB2 [Value] : Enterprise Database , It's expensive
[Key] : MySQL [Value] : Free Open SourceDatabase (no more, try MariaDB)
[Key] : Oracle [Value] : Enterprise Database , It's expensive
forEach loop...
[Key] : DB2 [Value] : Enterprise Database , It's expensive
[Key] : MySQL [Value] : Free Open SourceDatabase (no more, try MariaDB)
[Key] : Oracle [Value] : Enterprise Database , It's expensive

References

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
28 Comment threads
6 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
31 Comment authors
NichasiusinfojExpandablesSreejith Nchanaiah Recent comment authors
newest oldest most voted
tapan(i want use map in java and use map in create chat module)
Guest
tapan(i want use map in java and use map in create chat module)

please give me a chat mpdule while using a map please….?

soumya
Guest
soumya

hi,

This is very very good website for java and open source tutorials.

thanks

Javin Paul
Guest
Javin Paul

HashMap is very useful class in java but most people don’t understand difference between HashMap and Hashtable and when to use which , its important to learn correct usage of collection classes. to read about Hashtable vs HashMap see .

Cheers
Javin

Rakesh
Guest
Rakesh

good explanation of basic stuff in HashMap. I also found this link worth checking How HashMap works in Java

@mey
Guest
@mey

gud example….!

Anonymous
Guest
Anonymous

Thanks, good and simple example

Rajiv
Guest
Rajiv

Good Example for beginners, though I read couple of article on hashmap I found your example most simple and How HashMap works in Java theory most useful. Thanks

saphna
Guest
saphna

clear and concise example of hashmap 🙂

JavaLover
Guest
JavaLover

Really nice & simple program to illustrate Hash. Add tweet button. I’ll tweet this!!!

Daniel o
Guest
Daniel o

Hello MKYONG, I am thinking of a network monitoring system as as my final year project
can u give any help as to how to start and what is required (Java)

SHAFF
Guest
SHAFF

Very Good Example,
I have a dout..i am adding key and value to hash map value as arraylist.
(data getting from data base)
i want to display the key values in jsp page.
key — Time interval(24 hours)
Value –(login,uniqlogins)
if record is not there for particular interval then how i assign a key and value(default 0,0).
Ex: Time Interval : 00-23
for 3,4,5,6,7 there is no records for this interval
then i need to add 0,0 to values for that particular key.
please help me thanksin advance…

Maritha
Guest
Maritha

Hi There ! I’m from Indonesia and I’d like to ask how we’d show up the Key if we input the value. imagine I’m making dictionary coding using Map in Java. there my email, please so small reply to my email, I’d appreciate it if U share. Thank you, Mkyong !

TIN Sam
Guest
TIN Sam

This website is cool. Java is cool too. I just finish TPL program, and i used HashMap to store certain things. it makes my work simple and faster. http://vibeink.com

Ram Ramachandran
Guest
Ram Ramachandran

Good Work, Simple and Clear

sivaraj
Guest
sivaraj

Sir Pls help me, i stored the keys and Values.. I can get the value from the hash map, bt not in ordered.. i got it shuffled.. So how to get the HashMap values by the order, what i stored..

scqed
Guest
scqed

Great example, but can you comment on the compiler warning about hashmap being a generic type that it should be parameterized?

Bikash
Guest
Bikash

Simple and nice tutorial, but I have a problem where I need to keep track of number of occurrence of words every time I found that words in text. So I would like to know will HashMap will be good solution for me. Thanks

fasfas
Guest
fasfas

not bad../

Nicky Larson
Guest
Nicky Larson

Thank you man !

kon
Guest
kon

awesomeee ”/’

Kali Sastha
Guest
Kali Sastha

Thanks, I googling relate this. It is very useful and the examples are real time .

jai
Guest
jai

thank you for the good explanation.

ahsan
Guest
ahsan

Dear i want prediction according to text so is this useful in prediction

Eureka Todesky
Guest
Eureka Todesky

Thank you, Mr. Mkyong!

chanaiah
Guest
chanaiah

hashmap same key different values example in java

Expandables
Guest
Expandables

When i run this code ..i was getting this below error

HashMap.java:3: error: com.mkyong.core.HashMap is already defined in this compilation unit

import java.util.HashMap;

^

HashMap.java:12: error: incompatible types

Map mMap = new HashMap();

^

required: Map

found: HashMap

Note: HashMap.java uses unchecked or unsafe operations.

Note: Recompile with -Xlint:unchecked for details.

2 errors

Please let me know why i am getting this error

Thanks
Santhosh

infoj
Guest
infoj

To know about how HashMap works internally go though this link

http://netjs.blogspot.com/2015/05/how-hashmap-internally-works-in-java.html

Nichasius
Guest
Nichasius

Hi Mkyong, how would i iterate through a hashmap more than once in java ?
Such that after the last entry is reached, iteration starts from the
first entry for a specified number of times.