Main Tutorials

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 Author

author image
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

Subscribe
Notify of
34 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Nichasius
8 years ago

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.

infoj
8 years ago

To know about how HashMap works internally go though this link

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

Expandables
8 years ago

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

chanaiah
9 years ago

hashmap same key different values example in java

Eureka Todesky
9 years ago

Thank you, Mr. Mkyong!

ahsan
10 years ago

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

jai
10 years ago

thank you for the good explanation.

Kali Sastha
10 years ago

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

Sreejith N
9 years ago
Reply to  Kali Sastha

Nice Tutorial.. 🙂

kon
10 years ago

awesomeee ”/’

Nicky Larson
10 years ago

Thank you man !

fasfas
10 years ago

not bad../

Bikash
10 years ago

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

scqed
11 years ago

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

htmlman1
10 years ago
Reply to  scqed

It’s asking for something like this:

HashMap foo = new HashMap ();

Here instead of a “generic type” you’re specifying a specific type (i.e. the Integer.)
If you’re making a hashmap to store strings you could do something like this:

HashMap foo = new HashMap();

This would prevent the “generic type” warning.

sivaraj
11 years ago

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..

infoj
8 years ago
Reply to  sivaraj

Though it is very old question but it may help others. In HashMap order is not preserved.
If order has to be preserved then use LinkedHashMap instead.

Ram Ramachandran
11 years ago

Good Work, Simple and Clear

TIN Sam
11 years ago

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

Maritha
11 years ago

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
11 years ago
Reply to  Maritha

Hello @Maritha, if am not mistaken u are asking how to display ur hashmap values? if yes Map.values() will return collection of value in the map. u can use get to return each value by key. http://vibeink.com

SHAFF
11 years ago

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…

Daniel o
11 years ago

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)

Maritha
11 years ago
Reply to  Daniel o

a network monitoring system ? awesome.

JavaLover
11 years ago

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

saphna
12 years ago

clear and concise example of hashmap 🙂

Rajiv
12 years ago

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

Anonymous
12 years ago

Thanks, good and simple example

@mey
12 years ago

gud example….!

Rakesh
13 years ago

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

Javin Paul
13 years ago

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

soumya
13 years ago

hi,

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

thanks

tapan(i want use map in java and use map in create chat module)
13 years ago

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