HashMap example in Java

By: Charles Emailed: 1747 times Printed: 2434 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

The HashMap class uses a hash table to implement the Map interface. This allows the execution time of basic operations, such as get() and put(), to remain constant even for large sets.
The following constructors are defined: HashMap( )
HashMap(Map m)
HashMap(int capacity)
HashMap(int capacity, float fillRatio)

The first form constructs a default hash map. The second form initializes the hash map by using the elements of m. The third form initializes the capacity of the hash map to capacity. The fourth form initializes both the capacity and fill ratio of the hash map by using its arguments. The meaning of capacity and fill ratio is the same as for HashSet, described earlier.

HashMap implements Map and extends AbstractMap. It does not add any methods of its own. You should note that a hash map does not guarantee the order of its elements. Therefore, the order in which elements are added to a hash map is not necessarily the order in which they are read by an iterator.

The following program illustrates HashMap. It maps names to account balances. Notice how a set-view is obtained and used.

import java.util.*;
class HashMapDemo {
public static void main(String args[]) {
// Create a hash map
HashMap hm = new HashMap();
// Put elements to the map
hm.put("John Doe", new Double(3434.34));
hm.put("Tom Smith", new Double(123.22));
hm.put("Jane Baker", new Double(1378.00));
hm.put("Todd Hall", new Double(99.22));
hm.put("Ralph Smith", new Double(-19.08));
// Get a set of the entries
Set set = hm.entrySet();
// Get an iterator
Iterator i = set.iterator();
// Display elements
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();
// Deposit 1000 into John Doe's account
double balance = ((Double)hm.get("John Doe")).doubleValue();
hm.put("John Doe", new Double(balance + 1000));
System.out.println("John Doe's new balance: " +
hm.get("John Doe"));
}
}

Output from this program is shown here:

Ralph Smith: -19.08
Tom Smith: 123.22
John Doe: 3434.34
Todd Hall: 99.22
Jane Baker: 1378.0
John Doe's current balance: 4434.34

The program begins by creating a hash map and then adds the mapping of names to balances. Next, the contents of the map are displayed by using a set-view, obtained by calling entrySet(). The keys and values are displayed by calling the getKey() and getValue() methods that are defined by Map.Entry. Pay close attention to how the deposit is made into John Doe's account. The put() method automatically replaces any preexisting value that is associated with the specified key with the new value. Thus, after John Doe's account is updated, the hash map will still contain just one "John Doe" account.


Java Home | All Java Tutorials | Latest Java Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(45)


1. View Comment

Great tutorial. THX.

View Tutorial          By: Velvetin at 2009-03-21 11:05:19
2. View Comment

Nice Example...!

View Tutorial          By: Kuldeep Singh at 2009-10-18 23:58:17
3. View Comment

Hi there, what a nice example, very useful for me as a newbie! ~

View Tutorial          By: Yanny at 2009-12-10 12:34:26
4. View Comment

nice article..

View Tutorial          By: yummy at 2010-01-05 21:18:35
5. View Comment

It is very simple and understandable tutorial, the exact output after running this program is:

John Doe: 3434.34
Tom Smith: 123.22
Jane Baker: 1378.0
Todd Hall: 99.22
Ralph Smith: -19.08

John Doe's new balance: 4434.34


View Tutorial          By: Syed Turab at 2010-03-09 07:27:15
6. View Comment

gr8 tute dude.... ezy n nice..

View Tutorial          By: hErC!! at 2010-04-20 23:52:19
7. View Comment

The last output is not :John Doe's current balance: 4434.34
It is :John Doe's new balance: 4434.34


View Tutorial          By: Santosh at 2010-06-01 22:54:21
8. View Comment

nice

View Tutorial          By: rida at 2010-07-03 22:49:04
9. View Comment

Nice tutorial

View Tutorial          By: Sai at 2010-09-23 21:52:38
10. View Comment

Nice n simple ex!!!!!!!!!!!!!!!!!!!

View Tutorial          By: Siya at 2010-11-17 07:08:34
11. View Comment

YA IT'S VERY USEFUL

View Tutorial          By: JOTHIBASU at 2010-12-20 05:29:38
12. View Comment

nice one superb..

View Tutorial          By: Rajesh B at 2011-02-01 21:59:56
13. View Comment

Very Good Tutorial...
Very Good For Beginners...
ThankS.


View Tutorial          By: Yatiraj Chakre at 2011-02-02 04:28:57
14. View Comment

I need more example........

View Tutorial          By: niyaz d at 2011-02-20 23:44:56
15. View Comment

great resource

View Tutorial          By: Anonymous at 2011-04-14 03:14:43
16. View Comment

its very easy to understand and implements.

View Tutorial          By: ashish at 2011-05-20 03:12:07
17. View Comment

its good

View Tutorial          By: Srinu at 2011-05-26 23:57:18
18. View Comment

good. keep it up !

View Tutorial          By: hashu at 2011-06-21 01:49:59
19. View Comment

nice one

View Tutorial          By: priyaaaaaaaaaaaaaaa at 2011-06-21 08:04:39
20. View Comment

i din understand

View Tutorial          By: panda at 2011-07-14 09:35:36
21. View Comment

easy.......

View Tutorial          By: Suman at 2011-07-20 07:04:28
22. View Comment

Nice and easy to understand......Thanks for same

View Tutorial          By: vikas at 2011-07-21 07:44:30
23. View Comment

thanks..very nice and easy to understand for new java people like me..1st attribute in hm.put(key,Object) method works as a key.

View Tutorial          By: Ranjan at 2011-07-22 08:34:50
24. View Comment

Please help I want to map the data say username and password from database table to hashmap.Is it possible?

View Tutorial          By: akshat at 2011-07-25 12:49:06
25. View Comment

Simple Example. Understood. Thanx.
In akshat problem, I think not an good idea to keep user name and password in HashMap. HashMaps are not an order. If program has a login, it shoud read all the data in the HashMap. time consuming process.


View Tutorial          By: Amila Nadanda at 2011-07-28 06:21:05
26. View Comment

I do not understand this line:
Map.Entry me = (Map.Entry)i.next();


View Tutorial          By: hap Og at 2011-11-03 01:42:33
27. View Comment

great example for beginners. Thank you

View Tutorial          By: kumar at 2011-11-24 08:15:14
28. View Comment

this is simple example but need to more explanation required.

View Tutorial          By: Ramalingam at 2012-01-05 06:25:12
29. View Comment

How do you remove an element from the map?

View Tutorial          By: Shreejit at 2012-01-29 16:53:27
30. View Comment

very easy explain

View Tutorial          By: Rohit Bhojani at 2012-04-10 12:49:20
31. View Comment

Nice Article.

View Tutorial          By: Swathi Kumar at 2012-04-15 10:44:14
32. View Comment

Thanks.... Nice Example

View Tutorial          By: Nagarjuna at 2012-05-29 12:00:50
33. View Comment

hmmmmmm good

View Tutorial          By: Haritha chinnu at 2012-06-30 09:37:49
34. View Comment

Good one.....

View Tutorial          By: Ratnam.. at 2012-07-03 07:11:26
35. View Comment

answers to the questions asked by ranjan in comment #24

yes ranjan it is very task if u has small knowledge on jdbc,
i will write the code(only logic) regarding to ur question:

step1:load driver
step2:create connection
step3:create statement
step3:execute quire and store the result in ResultSet


Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con= DriverManager.getConnection("jdbc:odbc:FTW", "ur_name", "ur_lover_name");
//generally usernames are their names and passwords are their lover names//Step1
String st1="select uname, pass from Emp";
Statement st = con.createStatement();
ResultSet rs=st.executeQuery(st1);
Map m1 = new HashMap();
String my_name,my_lover_name;
while(rs.next())
{
my_name = rs.getString(1);//i.e user name
my_lover_name = rs.getString(2);//i.e passward
m1.put(my_name , my_lover_name); //here we add to our map

}
see how romantic this java is just enjoy


View Tutorial          By: A Sadist at 2012-07-05 12:13:45
36. View Comment

i'm doing project on hotel management...
and i'm using hashmap for save userid and password.
so.. how can i get items from hashmap into combobox?
means we create hashmap ani its date save in to ".dat" file.
and data save into file like..(userid:password:question1:answer1:true)
and i want to retrive question1,question2... in to combobox..
so tell me how.....Plsssssssss


View Tutorial          By: prashant patil at 2012-08-19 05:16:20
37. View Comment

Very nice one, it really helps me. Thank you very much :)

View Tutorial          By: eky1412 at 2012-09-10 03:45:07
38. View Comment

good one.......thanks

View Tutorial          By: raghubir at 2012-11-10 19:01:45
39. View Comment

Why the output list in the wrong order?

View Tutorial          By: Pavel at 2013-02-23 12:05:02
40. View Comment

Plz catch the exception to make the program complete! Use try catch!

View Tutorial          By: Naman at 2013-04-19 06:01:45
41. View Comment

how to comapre two hash map

View Tutorial          By: vinay at 2013-05-03 10:21:57
42. View Comment

Thanks for the simple tutorial on hashmaps. I am now able to dynamically structure HTML form POST or GET field and value parameters by using hashmaps in an Android application.

View Tutorial          By: ipkwena at 2013-08-19 09:02:49
43. View Comment

simple examples that i can understand ,.,,by the way, i am from china ~~

View Tutorial          By: Chriskuang at 2015-03-19 03:05:59
44. View Comment

Very Nice and Perfectly Understandable.....

View Tutorial          By: rex at 2015-04-16 12:27:03
45. View Comment

I want an example...to get multiple values using Single Key using any Map implemented class

View Tutorial          By: Madhu at 2015-07-13 19:57:14

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Charles
arraycopy example in Java
Action listeners in JSF
Automatically Including Preludes and Codas in JSP
Using realloc() Function in C
Handling multiple buttons in HTML Form in Struts
Fopen and Getc implementation program in C
Pointers to Structures example program in C
Pointers vs. Multi-dimensional Arrays in C
getch and ungetch in C
Bitwise Operators in C
Variables and Arithmetic Expressions in C
Differences between JavaServer Faces technology and Struts
assert() example program in C++
'double buffering' Sample program in J2ME
Converting Default Function Arguments in C++ to Java

More Tutorials in Java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Java File
Java String
Count number of vowels, consonants and digits in a String in Java
Reverse a number in Java
Student marks calculation program in Java
Handling Fractions in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program
MultiLevel Inheritance sample in Java
Multiple Inheritance sample in Java
Java program using Method Overriding
Java program to check if user input is an even number

More Latest News
Most Viewed Articles (in Java )
How to Send SMS using Java Program (full code sample included)
Using StringTokenizer in Java
Count number of vowels, consonants and digits in a String in Java
Method Overriding in Java
The Basic Structure of a Simple Java program
Vector example in Java
XML and Java - Parsing XML using Java Tutorial
Stack example in Java - push(), pop(), empty(), search()
Student marks calculation program in Java
append() in Java
wait(), notify() and notifyAll() in Java - A tutorial
Recursion in java
FileReader and FileWriter example program in Java
InetAddress Example program in Java
Use of try and catch in Java
Most Emailed Articles (in Java)
Update contents of a file within a jar file
Java Chat Client Sample Applet
Execute system commands in a Java Program
J2EE Services
Insert, Delete, Search, Print an int Array in Java
Get user input in Java
instanceof operator example in Java
Reading from a file and writing to a file using Java program
static keyword in Java
ThreadGroup Sample in Java
String Concatenation using Java
Sample Java Script that displays a movable clock
Multiple Inheritance sample in Java
Convert numbers to word as per Indian number system in java
Step by Step guide to setup freetts for Java