HashMap Implementation in Java - Java Collection Framework

In today's discussion we will talk about Map and HashMap in java. We will come to know properties of Java Hash Map and Examples of how to use HashMap in java to get more from it. Java Hash Map is a useful class implementation of Java Collection framework. HashMap implements Serializable, Cloneable and Map interfaces and extends AbstractMap class directly.

Java Hash Map is commonly used data structure that is used to store values along with a unique key associated with them. Java Hash Map is a Map implementation of HashTable, except that HashMap is not synchronized and permits null keys and values. Like other map implementation HashMap itself does not guarantees if the order of elements will remain same over the time or not.

Hash Map in Java provides a huge set of implementations, some of the basic and commonly used operations are listed below with proper example.

How to create a Hash Map in Java

A HashMap object can be obtained as shown below, generics specification is optional but it is always a good practice to tell JVM about the type of keys and content that is going to be stored in HashMap. Use of generics eliminates the need of explicit type casting.
// creating a new hash set with String  elements    
HashMap<Integer, String> hashMap = new HashMap<Integer, String>(); // using generics --Integer as key and String as value in this case   

How to add Elements to Java Hash Map - put()

HashSet provides two methods to associate key value pairs with it, put() adds a single value associated with a key and putAll() adds all key-value associations with hashMap as provided in other map to be added on. HashMap does not allows duplicate key values, so if the added Map has a key same as addto Map the object on addto Map will be replaced by object of added map.
HashMap<Integer, String> hashMap = new HashMap<Integer, String>(); // add to Map object  
hashMap.put(0,"apple"); // add single value pair  
HashMap<Integer, String> hashMap1 = new HashMap<Integer, String>(); // added map with putAll()  
hashMap.putAll(hashMap); // adding another Map to addto Map  
System.out.println(hashMap); // all unique values after adding a new map   

Get an element from a Hash Map in Java - get(key)

An element can be retrieved from a HashMap using a key, using get(key) method.
hashSet.get(0) // returns the element associated with the provided key.  

How to remove Elements from Java Hash Map - remove(key)

HashMap provides remove() method which removes one element as per the provided key.
hashMap.remove(0); // removed key-value pair associated with key '0'

How to make Java Hash Map Empty - clear()

HashMap provides clear() method to remove all key-value pairs from a HashMap, it makes HashSet an empty collection.
hashMap.clear(); // removes all key-value pairs of HashMap  
System.out.println(hashMap); //returns an empty HashMap  

How to clone a Hash Map in Java

Creates a shallow copy of HashMap instance but elements does not cloned themselves. While comparing a HashMap and its clone using .equals(), it always returns a 'true'.
//cloning a HashMap  
HashMap hashMapClone = (HashMap) hashMap.clone(); // returns a clone of HashMap with shallow copy of elemets  
System.out.println(hashMap.equals(hashMapClone)); // returns a true

How to compare Java Hash Map using .equals()

It returns true if the specified object is a Map with a identical size and both the HashMap objects represents same key-value mappings.
hashMap.equals(hashMap1); // returns a true if the specified object is a HashMap with a identical size and same key value mappings 

How to check if a Java Hash Map contains specified key or value - containsKey() and containsValue()

In HashMap we can check if the specified key or value is present or not, containsKey() returns true if the specified key is present in the Map and containsValue() returns a true if the specified value is present in the Map
hashMap.containsKey(0); // returns true if '0' is one of the all keys present in HashMap  
hashMap.containsValue("apple") // returns true if 'apple' is one of the value in HashMap 

How to convert a HashMap into String

HashSet provides toString() method that converts a HashMap in String form, each key-value pair is saperated by a ',' ,all pairs are enclosed within a '{}', and every key is given a assocaited value saperated by a '=' sign. Like {1=orange, 2=banana, 3=Lion}.
hashMap.toString() // returns a string representation of HashMap

How to convert HashMap into an Array

HashMap does not provides a toArray() method directly, but HashMap elements can be converted to array representation by converting HashSet to entrySet() first.
entrySet() returns a set view of key-value mappings in the HashMap, it represents a HashMap in a form like '[0=apple, 1=orange, 2=banana]'.
Now to this entrySet() can be converted to an array of elements.
hashMap.toString() // returns a string representation of HashMap

How to get size of a Java Hash Map

The size of a HashMap can be obtained using .size() method, it returns an integer value equals to the number of key-value pairs in the HashMap.
hashMap.size(); // returns an integer value equals to the number of key-value pairs in the HashMap

Get all keys set in a Java HashMap

HashMap provides keySet() method to obtain a set of all keys existing in the HashMap.
hashMap.keySet() // returns a set of all keys present in HashMap

How to get all values set in a HashMap in Java

HashMap provides values() method to get a collection of all values present in the HashMap in the form like, '[apple, orange, banana]'.
hashMap.values() // returns a collection of all values present in HashMap

How to iterate HashMap in Java

As Map does not belongs to collection interface, we do not have iterator() method to use directly, to iterate HashMap first convert it to entrySet() and iterate using Entry property of HashMap. As shown in the example below.
HashMap < Integer, String > hashMap = new HashMap < Integer, String > (); // create HashMap objecthashMap.put(0,"apple"); // add key value pairs to HashMaphashMap.put(1,"orange");hashMap.put(2,"banana");  Iterator iterator = (Iterator) hashMap.entrySet().iterator(); // apply iterator to entrySet()while(iterator.hasNext()){Map.Entry<Integer,String> keyValuePair = (Entry<Integer, String>) iterator.next(); // using Entry property of Map System.out.println(keyValuePair.getKey()+" : "+keyValuePair.getValue()); // printing key and values of HashMap }
It will give a output like :
0 : apple
1 : orange
2 : banana

In this blog we saw how to use HashMap and what is map and hashmap in java. We went through how to iterate hashmap and other examples of Hash Map in java. In upcoming blogs we will cover more topics and tricks on Java Collection Framework and its usage in Java Language.