Java hashmap a complete tutorial for beginners with examples, methods and functions, explanation of each class from java key value pair to put method. Check out the complete definition, examples part for each class method, map interface java, and creation of java hasmap from java key value pair put.
Check out the complete tutorial. Thanks to path thomas for a wonderful article contributed to java tutoring.
About Author : Path thomas is a Java Developer currently working at IBM india with more than 20+ years of experience in Java development. If you have any doubts related to this topic, do contact us or share your thoughts below. Our professional developers will always help you out.
[wp_ad_camp_1]
Table Of Contents:
[table id=3 /]
Everything That You Need To Know About Java HashMap
- What is Hashmap in Java ? ( Consider my Age is 5 and explain ) 😛
A : Okay Kid! There you go :
Suppose, we want to store a data of students and each student is represented by an object, we can use many provisions like arrays, linked-lists, array-lists, etc. Java HashMap is also similar to these kind of lists. With this, we can give an unique identity to each such object and access any such object in a very quick time.
The concept of hashing is used by the system to generate these unique identifiers. Programmer (we) need not to worry about the creation and management of these hash-codes (unique identifiers).
We just need to concentrate on creation and storage of objects (data). Any object can be identified (accessed) with a KEY value pair (internally the KEY is associated with the unique-identifier and the unique-identifier refers the actual object).
In this context the actual objects are referred as VALUEs. So broadly, a KEY is associated with a VALUE. The pair of KEY-VALUE should be understood to understand the HashMap Java.
[wp_ad_camp_2]
With the process of storing the objects (Values) and uniquely identifying them with a corresponding property (Key) involves some internal jig-jags, Java HashMap do not store the data in any particular order (ascending or descending). Even the elements are not stored in the same order that we have placed (inserted) them. In a view to making it possible for a minimum time, the order may change inside.
- Generally this are represented in different notations but all mean same :
- HashMap(KEY,VALUE)
- HashMap(Key, Value)
- HashMap(K,V)
Suppose we want to store data of a number of students (Values set) and each student should be identified by some Idno (Key) then each Student should be an object and each Idno should also be an object.
In that case we treat such HashMap as:
1 |
HashMap(Idno, Student) |
- Obviously, Idno and Student should be classes (or Interfaces).
Similarly, if we want to store data of a number of mobile phones and imei numbers are used to identify them, then our syntax could be something like,
[wp_ad_camp_3]
1 |
HashMap(IMEI, MobilePhone) |
- where IMEI and MobilePhone are existing classes(interfaces).
The size of the objects (no. of elements in each object) can be as bigger as we want. There is no limit on them. But in the following example we are storing data of students (who are identified by Idnos).
- where the Student is just a String and
- Idno is just an Integer.
In that case the corresponding Java HashMap can be like HashMap(Integer, String).
Example:
1 |
HashMap<Integer, String> hm = new HashMap<Integer, String>(); |
With the above statement the system can understands that we are going to store a set of String objects (Values) and each such object is identified by an Integer object (Key).
We are going to represent Idnos with Integer class and Student name with String class.
Here we go different Java map methods, and their functions with examples.Table Of Contents:
[table id=4 /]
1. put():
- Definition : To store a student data we can specify Integer (Idno) and String (Name) like the following.
Example:1
1 |
hm.put(17,"abhishek"); |
We can store any number of such records (Entries) in the Put Method java.
Example:2
1 2 3 4 5 |
hm.put(50,"ajith"); hm.put(71,"alekhya"); hm.put(11,"amani"); |
2.Java HashMap Get()
Definition : Once such data is placed in the Map, we can retrieve it using a valid Key.
As an Integer is Key in our example, we can specify a Key so that the system will give corresponding Object (String, in this case).
[wp_ad_camp_4]
Example Java Hashmap Get() – 1:
1 2 3 |
String s=hm.get(50); System.out.println(s); // will print “ajith” |
Example Java Hashmap Get() – 2:
1 2 3 |
String t=hm.get(11); System.out.println(t); // will print “amani” |
- If there is no Value associated with the given Key then null is returned by get().
We have written a complete example that creates a object, puts some data, retrieves. Check out theExample Below:
Example Program Put() and Get():
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import java.util.*; class Check { public static void main(String arg[]) { HashMap<Integer, String> hm=new HashMap<Integer, String>(); hm.put(17,"abhishek"); hm.put(50,"ajith"); hm.put(71,"alekhya"); hm.put(11,"amani"); String s=hm.get(50); //s="ajith"; System.out.println(s); s=hm.get(11); // s="amani"; System.out.println(s); } } |
3. EntrySet():
[wp_ad_camp_3]
- Definition : In the following example, we will put some data in the Map and retrieve all the data to print it (instead of retrieving random data). #Print hashmap Java#
Example Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
import java.util.*; class Check { public static void main(String arg[]) { HashMap<Integer, String> hm=new HashMap<Integer, String>(); hm.put(17,”abhishek”); hm.put(57,”anusha”); hm.put(50,”ajith”); hm.put(33,”aparna”); hm.put(71,”alekhya”); hm.put(99,”babitha”); hm.put(11,”amani”); Iterator trav=hm.entrySet().iterator(); while(trav.hasNext()) { Map.Entry record=(Map.Entry)trav.next(); //will give next (Key, Value) pair System.out.println(record.getKey()+”–>”+record.getValue()); } } } |
Output:
1 2 3 4 5 6 7 |
17–>abhishek 33–>aparna 50–>ajith 99–>babitha 71–>alekhya 57–>anusha 11–>amani |
- If we observe the above program output, we can clearly understand that the order of retrieval is not the same as the order in which we have placed the data.
In the above example, we have used Iterator interface to travel through the Maps.
The entrySet() method will return a Set of entries (records where each record is a Key-Value pair).
- To travel through such a Set, we have taken an Iterator.
Example:1
1 |
Iterator trav=hm.entrySet().iterator(); |
This statement can be understood by splitting it into two statements like the following…
Example:2
1 2 3 |
Set set=hm.entrySet(); Iterator trav=set.iterator(); |
The Iterator interface has methods to check whether we have any more elements(hasNext()), to get next element (next()), etc.
In the loop, we are verifying whether any more elements are remaining and getting each one of them.
A key Value pair can be held by a Map.Entry object. The next() method of Iterator gives us the next available object (it can be of any type) and we are converting it to Map Entry type.
Example:
1 |
Map.Entry record=(Map.Entry)trav.next(); |
Once the Map.Entry object (a record) is available, we can retrieve the Key and Value separately using getKey() and getValue().
Example:
1 |
System.out.println(record.getKey()+"-->"+record.getValue()); |
- The getKey() and getValue() methods return an Object and they should be converted to the required type. So the above statement can be better understood with the following separated statements.
Example:
1 2 3 4 5 |
Integer key=(Integer)record.getKey(); String value=(String)record.getValue(); System.out.println(key+"-->"+value); |
4.Java Hashmap keyset()
Definition : Instead of using entrySet() (as in the above example), we can use keyset() and get the same result. The keyset() method gives us a set of Keys (but no Values).
So the Iterator will travel through each Key and use get() method on Maps.
We can see corresponding code below. In this case we supply the each key as argument to get().
Example:1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
Set set=hm.keySet(); Iterator trav=set.iterator(); while(trav.hasNext()) { Integer key=(Integer)trav.next(); //will give next Key String value=hm.get(key); System.out.println(key+"-->"+value); } |
5.values()
Definition : suppose we want to retrieve only the values (Keys not required) then we can use the values() method.
This method will return a collection of Value Objects. We just can iterate through the collection to retrieve each Value.
Example Program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
class Check { public static void main(String arg[]) { java.util.HashMap<Integer, String> hm=new java.util.HashMap<Integer, String>(); hm.put(81,”bhanusri”); hm.put(57,”anusha”); hm.put(23,”bharadwaj”); hm.put(33,”aparna”); hm.put(85,”bharath”); hm.put(99,”babitha”); hm.put(66,”bindu”); Collection col=hm.values(); Iterator trav=col.iterator(); while(trav.hasNext()) { String value=(String)trav.next(); // will give next Value System.out.println(value); } } } |
Output:
1 2 3 4 5 6 7 |
bhanusri aparna bindu babitha bharath bharadwaj anusha |
Example Program : 2 Taking an object as a argument in Hashmap Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
import java.util.*; class Xyz { String name; String clg ; String branch ; double per; Xyz(String s1,String s2,String s3,double p) { name=s1; clg=s2; branch=s3; per=p; } } class Check { public static void main(String arg[]) { HashMap<Integer, Xyz> hm=new HashMap<Integer, Xyz>(); Xyz x1=new Xyz("goutham","SNIST","cse",68.5); Xyz x2=new Xyz("kanakesh","SNIST","ecm",70); Xyz x3=new Xyz("rahul","SNIST","ecm",75); Xyz x4=new Xyz("vasista","SNIST","ECM",80); Xyz x5=new Xyz("narayana","SNIST","EEE",85); hm.put(1,x1); hm.put(2,x2); hm.put(3,x3); hm.put(4,x4); hm.put(5,x5); Iterator trav=hm.entrySet().iterator(); while(trav.hasNext()) { Map.Entry record=(Map.Entry)trav.next(); //will give next (Key, Value) pair Xyz j=(Xyz)record.getValue(); System.out.println(record.getKey()+" "+j.name+" "+j.clg+" "+j.branch+" "+j.per); } } } |
Output:
1 2 3 4 5 6 |
key name clg branch percentage 1 goutham SNIST CSE 68.5 2 kanakesh SNIST CSE 70.0 3 rahul SNIST CSE 75.0 4 vasista SNIST CSE 80.0 5 narayana SNIST CSE 85.0 |
Example Program – 3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
import java.util.*; class Key { String topic,specialization; Key(String t,String s) { topic=t; specialization=s; } public String toString() { return("> "+topic+"-"+specialization); } } class Value { String description,since,record; Value(String d,String s,String r) { description=d; since=s; record=r; } public String toString() { return("\t"+description+"\n\t"+since+"\n\t"+record+"\n"); } } class HashMapExample { public static void main(String arg[]) { Key k1,k2, k3; k1=new Key("sachin","cricket"); k2=new Key("sachin","music"); k3=new Key("newton","science"); Value v1,v2,v3; v1=new Value("Sachin Ramesh Tendulkar", "playing international cricket since 1989", "one of the best batsmen in cricket & highest run scrorer in test & ODIs\n\tfirst Indian sports person to receive BharathRatna\n\tnamed after famous composer SDBurman"); v2=new Value("Sachin Dev Burman","started career in 1937 with bengali movies then moved to Bollywood","one of the best composers in India\n\tgiven music to nearly 100 movies"); v3=new Value("Isaac Newton","Sir Isaac Newton has been in scientic field since 1665","he is famous for his laws of motion and universal gravitation formulae\n\this and his father names are same\n\the is a british national"); HashMap<Key,Value> know=new HashMap<Key,Value>(); know.put(k1,v1); know.put(k2,v2); know.put(k3,v3); System.out.println(k1); System.out.println(know.get(k1)); System.out.println(k2); System.out.println(know.get(k2)); System.out.println(k3); System.out.println(know.get(k3)); } } |
OutPut:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
> sachin-cricket Sachin Ramesh Tendulkar playing international cricket since 1989 one of the best batsmen in cricket & highest run scrorer in test & ODIs first Indian sports person to receive BharathRatna named after famous composer SDBurman > sachin-music Sachin Dev Burman started career in 1937 with bengali movies then moved to Bollywood one of the best composers in India given music to nearly 100 movies > newton-science Isaac Newton Sir Isaac Newton has been in scientic field since 1665 he is famous for his laws of motion and universal gravitation formulae his and his father names are same he is a british national |
6.List Of Other Methods With Examples And Sample Program
- size() gives the count of entries (<Key, Value> pairs).
- containsKey() tells whether a specified Key exists or not.
- containsValue() tells whether a specified Value exists or not
- remove() removes the Entry corresponding to the specified Key
- isEmpty() tells whether the it’s is empty
- clear() removes all entries from and making the HashMap empty.
Here we go example with the combination of above Other methods
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
class Check { public static void main(String arg[]) { java.util.HashMap<Integer, String> hm; hm=new java.util.HashMap<Integer, String>(); hm.put(81,”bhanusri”); hm.put(57,”anusha”); hm.put(23,”bharadwaj”); hm.put(33,”aparna”); hm.put(85,”bharath”); hm.put(99,”babitha”); hm.put(66,”bindu”); System.out.println(hm.size()); // “7” System.out.println(hm.get(33)); // “aparna” System.out.println(hm.containsKey(65)); // “false” as Key 65 does not exist System.out.println(hm.containsKey(66)); // “true” as Key 66 exists System.out.println(hm.containsValue(“anusha”)); // “true” as anusha exists System.out.println(hm.get(32)); // “null” as there is no Value associated with the Key 32 System.out.println(hm.remove(57)); // “anusha” as it is removed from HashMap System.out.println(hm.remove(10)); // “null” as no Entry can be removed (no Entry exists with the Key 10) System.out.println(hm.remove(“babitha”)); // “null” as no Entry can be removed (no Entry exists with the Key “babitha”–>”babitha” exists in the HashMap but it is a Value not a Key) System.out.println(hm.size()); // “6” as one Value is removed System.out.println(hm.containsValue(“anusha”)); // “false” as anusha does not exists (is removed) System.out.println(hm.isEmpty()); // “false” as some elements exists hm.clear(); //removes all Entries System.out.println(hm.size()); // “0” as all Entries are removed System.out.println(hm.isEmpty()); // “true” as no elements exists } } |
7. Java HashMap Clone()
Definition : It can be used to create another copy of a HashMap Java. Once the new copy is created (cloned) any modifications on original Map will not affect the cloned copy.
An example can be seen below.
Example For Clone():
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
import java.util.*; class Check { public static void main(String arg[]) { Iterator trav; HashMap<Integer, String> first=new HashMap<Integer, String>(); first.put(23,”chashmi”); first.put(55,”divya”); first.put(66,”dheeraj”); first.put(60,”deepthi”); first.put(93,”gowtham”); first.put(90,”durbesh”); HashMap<Integer, String> second=(HashMap<Integer, String>)first.clone(); System.out.println(first.remove(60)+” removed from first”); System.out.println(first.remove(90)+” removed from first”); System.out.println(“\nvalues in first…”); trav=first.values().iterator(); while(trav.hasNext()) { System.out.println(“\t”+trav.next()); } System.out.println(“\nvalues in second…”); trav=second.values().iterator(); while(trav.hasNext()) { System.out.println(“\t”+trav.next()); } } |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
deepthi removed from first durbesh removed from first values in first… dheeraj chashmi divya gowtham values in second… dheeraj chashmi divya durbesh deepthi gowtham |
From, the above example we have 6 Entries (Key, Value pairs) in the first one. We have cloned it into second so all the 6 Entries will be in second HashMap also.
- Then we removed 2 entries from first-one but this change will not affect the second-one.
- After the removal first one it contains 4 entries and the second HashMap contains 6 entries.
8.putAll()
Definition : In this method we used to add all elements of one Map into another Map.
Suppose we write second.putAll(first), then all entries of first HashMap will be added to the entries of second HashMap. With this the second one will become bigger. The following example will demonstrate it.
Example PutAll():
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
import java.util.*; class Check { public static void main(String arg[]) { Iterator trav; HashMap<Integer, String> first=new HashMap<Integer, String>(); first.put(23,”chashmi”); first.put(55,”divya”); first.put(66,”dheeraj”); first.put(60,”deepthi”); first.put(93,”gowtham”); first.put(90,”durbesh”); // 6 entries in first up to this point HashMap<Integer, String> second=new HashMap<Integer, String>(); second.put(30,”harikumar”); second.put(82,”hariprakash”); // 2 entries in second up to this point second.putAll(first); // all entries (6) of first are added to second. so second contains a total of 8 entries first.remove(66); first.remove(55); // 2 entries removed from first System.out.println(first.size()); // first contains 4 System.out.println(second.size()); //second contains 8 } } |
9. Important Points To Note:
- We cannot have duplicate keys. One Key can be associated with one Value only.
- We can have a maximum of one null Key only.
- We can have any number of null Values.
- We can have duplicate p<Integer, String>(); values. It means two or more keys can be associated with a same Value.
- A HashMap implements Map and extends the abstract class AbstractMap.
Here is one example to show:
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
HashMap<Integer, String> first=new HashMap<Integer, String>(); first.put(23,”chashmi”); first.put(55,”divya”); first.put(66,”gowtham”); first.put(60,”deepthi”); first.put(93,”gowtham”); first.put(90,”durbesh”); first.put(23,”fathima”); System.out.println(first.get(23)); // fathima System.out.println(first.size()); // 6 System.out.println(first.get(66)); //gowtham System.out.println(first.get(93)); //gowtham |
- From, the above code, we have made an Entry with Key 23 and Value “chashmi” and later made another Entry with same Key 23 and Value “fathima” then the Key 23 will be associated with “fathima” only and “chashmi” will have no relation with 23. Even though we made 7 entries, the system stores 6 entries only as 23 is duplicated. We have two keys 66 and 93 and both have a same Value “gowtham”.
Comparison With Similar Collections
Hasmaps are :
- Methods are unsynchronized where as hashtable methods are synchronized.
- Can have null Key and null Values where as hashtable does not allow.
- It is used to associate a Key with a corresponding Value.
- It is a collection of Key,Value pairs where as HashSet is a collection of only Values.
Package Information
- The class HashMap is in the package java.util
- The interface Iterator is in the package java.util.
- The interface Map is in the package java.util.
- The interface Map.Entry is in the package java.util.
Hope you got an idea about what are Java HasMaps.