Java HashMap example

HashMap is an object that stores both “key/value” as a pairs. In this article, we show you how to create a HashMap instance and iterates the HashMap data.


["mkyong","1000.00"] = ["key","value"]

In above, “mkyong” is the key , “1000.00” is the value. By given a key “mkyong”, you can get the value “1000.00”.

Example

See full example of using HashMap.


package com.mkyong.core;

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

public class Number {
	public static void main(String[] args) {
		try {

			Map mMap = new HashMap();
			mMap.put("PostgreSQL", "Free Open Source Enterprise Database");
			mMap.put("DB2", "Enterprise Database , It's expensive");
			mMap.put("Oracle", "Enterprise Database , It's expensive");
			mMap.put("MySQL", "Free Open SourceDatabase");

			Iterator iter = mMap.entrySet().iterator();

			while (iter.hasNext()) {
				Map.Entry mEntry = (Map.Entry) iter.next();
				System.out.println(mEntry.getKey() + " : " + mEntry.getValue());
			}

			mMap.put("Oracle", "Enterprise Database , It's free now ! (hope)");

			System.out.println("One day Oracle.. : " + mMap.get("Oracle"));

		} catch (Exception e) {
			System.out.println(e.toString());
		}
	}
}

Output


PostgreSQL : Free Open Source Enterprise Database
MySQL : Free Open SourceDatabase
Oracle : Enterprise Database , It's expensive
DB2 : Enterprise Database , It's expensive
One day Oracle.. : Enterprise Database , It's free now ! (hope)

About the Author

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

Comments

Leave a Reply

avatar
newest oldest most voted
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.

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

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

chanaiah
Guest
chanaiah

hashmap same key different values example in java

Eureka Todesky
Guest
Eureka Todesky

Thank you, Mr. Mkyong!

ahsan
Guest
ahsan

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

jai
Guest
jai

thank you for the good explanation.

Kali Sastha
Guest
Kali Sastha

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

Sreejith N
Guest
Sreejith N

Nice Tutorial.. :)

kon
Guest
kon

awesomeee ”/’

Nicky Larson
Guest
Nicky Larson

Thank you man !

fasfas
Guest
fasfas

not bad../

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

scqed
Guest
scqed

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

htmlman1
Guest
htmlman1

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

infoj
Guest
infoj

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
Guest
Ram Ramachandran

Good Work, Simple and Clear

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

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

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

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)

Maritha
Guest
Maritha

a network monitoring system ? awesome.

JavaLover
Guest
JavaLover

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

saphna
Guest
saphna

clear and concise example of hashmap :)

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

Anonymous
Guest
Anonymous

Thanks, good and simple example

@mey
Guest
@mey

gud example….!

Rakesh
Guest
Rakesh

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

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

soumya
Guest
soumya

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)
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….?