Java Hashmap Tutorial With Examples - Java Tutoring
Beginners Programs :

Java Hashmap Tutorial With Examples – Java Tutoring

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.

Table Of Contents:

Sr.NoComplete Guide For Beginners
1.What Is Java Hashmap/Definition
2.What Are Different Notations?
3.List Of Different Hashmap Class Methods
4.Important Points To Note
5.Comparison With Similar Collections
6.Package Information

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.

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 :
  1. HashMap(KEY,VALUE)
  2. HashMap(Key, Value)
  3. 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:

  • 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,

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

  1. where the Student is just a String and
  2. Idno is just an Integer.

In that case the corresponding Java HashMap can be like HashMap(Integer, String).

Example:  

 

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:

Sr.NoList Of Methods/Def/Examples/Sample Programs
1.Put() Def/Examples
2.Get() Def/Examples
3.Entryset() Def/Examples
4.Keyset() Def/Examples
5.Values() Def/Examples
6.Other Methods: Size(), Containskey(), ContainsValue(), Remove(), IsEmpty(), Clear().
7.Clone() Def/Examples
8.PutAll() Def/Examples

1. put():

  • Definition : To store a student data we can specify Integer (Idno) and String (Name) like the following.

Example:1

We can store any number of such records (Entries) in the Put Method java.

Example:2

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

Example Java Hashmap Get() – 1:

 

Example Java Hashmap Get() – 2:

 

  • 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():

3. EntrySet():

  • 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:

Output:

 

  • 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

This statement can be understood by splitting it into two statements like the following…

Example:2

 

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:

 

Once the Map.Entry object (a record) is available, we can retrieve the Key and Value separately using getKey() and getValue().

Example:

 

  • 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:

 

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

 

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:

Output:

Example Program : 2 Taking an object as a argument in Hashmap Java

Output:

Example Program – 3 

OutPut:

6.List Of Other Methods With Examples And Sample Program
  1. size() gives the count of entries (<Key, Value> pairs).
  2. containsKey() tells whether a specified Key exists or not.
  3. containsValue() tells whether a specified Value exists or not
  4. remove() removes the Entry corresponding to the specified Key
  5. isEmpty() tells whether the it’s is empty
  6. clear() removes all entries from and making the HashMap empty.

Here we go example with the combination of above Other methods 

Example:

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():

Output:

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():

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:

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