Java Map and HashMap Tutorial With Examples
In Java The Map interface defines the basic support for storing
key−value pairs in collections where each key can map to, at most, one value. While Map is part of the framework, it does not extend from the Collection interface. Instead, it is the root of its own hierarchy.There are four concrete implementations of the Map interface: HashMap, WeakHashMap,TreeMap, and the historical Hashtable.
The Map is used for storing collection of data in the form of key-value or name-value pair. Example Phone Book where you find the number of person or company using its name which is nothing but a key to locate the record uniquely.
HashMap Class
The HashMap is the most commonly used implementation of the Map interface. HashMap provides a basic key−value map where the elements are unordered and unsorted.
Creating HashMap
You can use one of the following constructor and new operator to create a HashMap object.
- public HashMap()
- public HashMap(int initialCapacity)
- public HashMap(int initialCapacity, float loadFactor)
In Java 5.0 onward you can also create a type specific HashMap meaning that the keys and values will be predefined and you cannot add anything unlike in non-type safe collection.
Example of type safe HashMap:
Map phoneBook = new HashMap() ;
Adding Elements In HashMap
Now you have created a HashMap instant lets add few entries in it. You can use put() method of Map interface to add name-value pair.
Example :
phoneBook.put("Dolly" , "9988554")
Copying All key-value pairs
You can use putAll() method of Map interface to copy name-value pairs from one Map to Another.
public void putAll(Map map)
Iterating over Map Or HashMap :
Please refer my previous post on How to iterate over Map or Hash Map.
Putting it All Together: Let see an example of HashMap to understand it better.
Example of HashMap
package com.tutorialswithexamples.hashmap; import java.util.HashMap; import java.util.Map; /** * Example of HashMap to demonstrate basic use. * */ public class HashMapExample { public HashMapExample() { super(); } public static void main(String[] args) { //create an instance of HashMap to Store Phone Number Map exampleUserMap = new HashMap(); //Populate example map with values exampleUserMap.put("Sam", 258963147); exampleUserMap.put("John", 5874569); exampleUserMap.put("Sunny", 58963147); exampleUserMap.put("Linda", 523658); for (Map.Entry entry : exampleUserMap.entrySet()) { System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); } } }
Example Output

As you can see we have used Map.Entry interface which represent a key-value pair in Map.
Share and Enjoy
How To Convert Array To Collection, ArrayList And Set Java TreeMap Tutorial and Examples
