HashMap in Java

Java HashMap class implements the map interface by using a hashtable. It inherits AbstractMap class and implements Map interface.

  • Key-Pair : A HashMap contains values based on the key
  • Unique : It contains only unique keys and it can have duplicate values
  • null value : It can have one null key and multiple null values.
  • random order : It maintains no order, so you should not access with index. And order may change over time.
  • Not Thread Safe : Java HashMap is not thread safe, for multi-threaded environment you should use ConcurrentHashMap class instead of HashMap
  • Constant Time : HashMap gives constant time performance for the operations like get() and put() methods
  • Capacity : Default initial capacity of HashMap is 16.

ArrayList and it's methods

Create a HashMap

When there is no parameter defined while creating HashMap default Initial Capacity(16) and Default load factor(75%) will be used.

Below is the constructor of HashMap


public class HashMap<K,V> extends AbstractMap<K,V>
        implements Map<K,V>, Cloneable, Serializable {
	/**
	* The default initial capacity - MUST be a power of two.
	*/
	static final int DEFAULT_INITIAL_CAPACITY = 16;
	/**
	* The load factor used when none specified in constructor.
	*/
	static final float DEFAULT_LOAD_FACTOR = 0.75f;
    public HashMap() {
			this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
	}
}			
Capacity :

the number of elements a particular collection can hold, yes, collection do not have limit that does not mean java will provide space for all the unlimited members at one shot, the space will be allocated only when it reaches a storage limit.

Load Factor :

As I said above, load factor decides when to increase the capacity of the collection, Hash map has load factor of 75% which means HashMap will not increase its capacity till 75% space is occupied that is 12 elements out of 16 element. On the insertion of 13th element HasMap increases the size.

This HashMap can contain up to 16 element and resizing of HashMap will occur when 13th element will be inserted. This is because load factor is 75%(.75) and this threshold will be crossed when you add 13th element(12+1).

You can also provide custom initial capacity and loadFactor. But initial capacity can not be more than maximum capacity (2 power 30) and load factor can not be zero or negative number

Creation of HashMap in Java


// basic syntax
Map<K, V> basicHashMap = new HashMap();
// map of r key as string and value as integer
Map<String, Integer> hash = new HashMap();

HashMap<String, Integer> hashMap = new HashMap();
			


Sample usage of the HasMap


public class CreateHashMapSample{
    public static void main(String[] args) {
        // Create HashMap
        Map<String, Integer> hMap = new HashMap();

        // Adding keys and  values to a HashMap
        hMap.put("One", 1);
        hMap.put("Two", 2);
        hMap.put("Three", 3);

        System.out.println(hMap);
    }
}			


Output of the sample HashMap program



{Three=3, One=1, Two=2}		


Constructors of HashMap

HashMap has four constructor, these constructors are designed to provide options for users.

HashMap with no params : It is the default constructor which creates an instance of HashMap with initial capacity 16 and load factor 0.75.


Map<K, V> basicHashMap = new HashMap();			


HashMap with Capacity : This HashMap constructor creates a HashMap instance with specified initial capacity and with default load factor of 0.75.


Map<K, V> basicHashMap = new HashMap(int initial capacity);			


HashMap with Capacity & Load Factor: This constructor creates a HashMap instance with specified initial capacity and specified load factor.


Map<K, V> basicHashMap = new HashMap(int initial capacity, float loadFactor);			


HashMap with another Map: It creates instance of HashMap with member of the provided map. The HashMap is created with default load factor (0.75) and an initial capacity sufficient to hold the mappings in the specified Map.


Map<K, V> basicHashMap = new HashMap(Map map)			


Methods Present in HashMap in Java

  • boolean isEmpty()
  • Object put(Object key, Object value)
  • int size()
  • get(Object key)
  • void clear()
  • boolean containsKey(Object key)
  • boolean containsValue(Object value)
  • Object clone()
  • Set entrySet()
  • Set keySet()
  • Collection values()
  • Methods introduced in HashMap in Java 8

  • computeIfAbsent()
  • computeIfPresent
  • compute
  • forEach
  • getOrDefault
  • merge
  • putIfAbsent
  • remove
  • replace
  • boolean replace(K key, V oldValue, V newValue)
  • replaceAll
Sample program for HashMap, below methods will be using HashMap from this program.

public class CreateHashMapSample{
    public static void main(String[] args) {
        // Create HashMap
        Map<String, String> hMap = new HashMap();
    }
}			

boolean isEmpty()

It checks whether the map is empty. If there are no key-value mapping present in the map then this function returns true else false.


 // Create HashMap
Map<String, String> hMap = new HashMap();

System.out.println("Member of the Map : "+hMap);
System.out.println("Is Map empty : " + hMap.isEmpty());			


Output of isEmpty()


Member of the Map : {}
Is Map empty : true	

Object put(Object key, Object value)

Creates a key with respective value in the HashMap. If map contains the same key with different value then the old value is replaced with new Value


Map<String, String> hMap = new HashMap();
        
System.out.println("Map before addition : "+hMap);
// add new value
hMap.put("microsoft", "Bing");
System.out.println("Map after addition of key-value: "+hMap);
// update the value with sam key
hMap.put("microsoft", "Operating System");
System.out.println("Map after replacement of key-value: "+hMap);			


Output of put()


Map before addition : {}
Map after addition of key-value: {microsoft=Bing}
Map after replacement of key-value: {microsoft=Operating System}			

int size()

Returns the number of key-value pairs present in the HashMap


Map<String, String> hMap = new HashMap();

// add new values
hMap.put("microsoft", "Bing");
System.out.println("Map members : "+hMap);
System.out.println("Map size : "+hMap.size());

System.out.println("\n*******Adding win10 (second entry)*******");
hMap.put("win10", "Operating System");
System.out.println("Map members : "+hMap);
System.out.println("Map size : "+hMap.size());			


Output of size()


Map members : {microsoft=Bing}
Map size : 1


*******Adding win10 (second entry)*******
Map members : {win10=Operating System, microsoft=Bing}
Map size : 2
			

void clear()

clear() method will remove all the entries from the HashMap


 Map<String, String> hMap = new HashMap();
        
// add new values
hMap.put("microsoft", "Bing");
hMap.put("win10", "Operating System");
System.out.println("Map members before clearing : "+hMap);
hMap.clear();
System.out.println("Map members after clearing : "+hMap);			


Output of clear() in HashMap


Map members before clearing : {win10=Operating System, microsoft=Bing}
Map members after clearing : {}			

get(Object key)

Returns the value mapped to the specified key, or null if there is no mapping for the key.


Map<String, String> hMap = new HashMap();
        
// add new values
hMap.put("microsoft", "Bing");
hMap.put("win10", "Operating System");
System.out.println("Get value of 'win10' from Map : " +hMap.get("win10"));			


Output of get() method


Get value of 'win10' from Map : Operating System			

remove(Object key)

Removes key from the map along with its value


Map<String, String> hMap = new HashMap();
        
// add new values
hMap.put("microsoft", "Bing");
hMap.put("win10", "Operating System");
System.out.println("Map members : " +hMap);
hMap.remove("win10");
System.out.println("Map members after removal of 'win10' : " +hMap);			


output after removal of element


Map members : {win10=Operating System, microsoft=Bing}
Map members after removal of 'win10' : {microsoft=Bing}			

void putAll(Map<? extends K, ? extends V> m)

Copies all of the mappings from the specified map to this map. if we have any keys in both the maps then map the key-value present in the map that we are adding will replace the key-value present in out source map. (highlighted in output)


 Map<String, String> hMap = new HashMap();
System.out.println("Members of hMap: " +hMap);

Map<String, String> kiddyMap = new HashMap();
kiddyMap.put("larry", "Google");
kiddyMap.put("gates", "microsoft");
System.out.println("Members of Kiddy : "+kiddyMap);

hMap.putAll(kiddyMap);
System.out.println("Members of hMap after adding Kiddy");
System.out.println(hMap);			


Output of putAll() hashmap-replace-putall-java

boolean containsKey(Object key) & containsValue(Object value)

containsKey() method will return true if the given key is present in the map otherwise false, so does containsValue() as well.


Map<String, String> hMap = new HashMap();
hMap.put("aa", "bbbb");
hMap.put("larry", "Youtube");
System.out.println("Members of hMap: " +hMap);

System.out.println("Contains Key 'abc' : " +hMap.containsKey("abc"));
System.out.println("Contains Value 'Youtube' : " +hMap.containsValue("Youtube"));			


output of containsKey & containsValue in HashMap


Members of hMap: {aa=bbbb, larry=Youtube}
Contains Key 'abc' : false
Contains Value 'Youtube' : true			

Set keySet()

Returns keys present in the map as Set collection.

values()

values() method returns all the values present in the map.


Map<String, String> hMap = new HashMap();
hMap.put("aa", "bbbb");
hMap.put("larry", "Youtube");

System.out.println("Keys Presesnt in Map : " +hMap.keySet());
System.out.println("Values present in Map : " +hMap.values());			


Output of keySet() and values()


Keys Presesnt in Map : [aa, larry]
Values present in Map : [bbbb, Youtube]			


Default Constructor in selenium and Java

Iterate through HashMap

Iterate over a collection or data set in Java is a very common task. You can use it to print or manipulate the data.

Iterate through a HashMap using for each :

For each loop is nothing but enhanced for loop, the difference is this loop will not have any loop control variable but the the loops starts with the first item in the collection and incrementally goes till th end.

Once it reaches collection end then loops gets terminated and for every time we will receive the current collection member to perform some operation.


public static void main(String[] args) {
	Map<String, String> map = new HashMap<String, String>();
	map.put("firstKey", "firstValue");
	map.put("secondKey", "secondValue");
	//enhanced for loop
	for (Map.Entry<String, String> entry : map.entrySet()) {
		System.out.println(entry.getKey() + " = " + entry.getValue());
	}
}			


Output of enhanced for loop iteration


firstKey = firstValue
secondKey = secondValue			

Iterate through HashMap with Lambda Expressions in Java 8 :

we can iterate through Map using lambda function in Java 8.


public static void main(String[] args) {
	Map<String, String> map = new HashMap<String, String>();
	map.put("firstKey", "firstValue");
	map.put("secondKey", "SecondValue");
	
	// for each with lambda
	map.forEach((key,value) -> System.out.println(key + " = " + value));
}		

Iterate through HashMap using Iterator :

This method uses java.util.Iterator to go through the HashMap, Iterator will be created to the Map object and the pointer point to first element of the object and moves further member once the next() method occurs.


public static void main(String[] args) {
	Map<String, String> map = new HashMap<String, String>();
	map.put("firstKey", "firstValue");
	map.put("secndKey", "secondValue");
	Iterator> it = map.entrySet().iterator();
	while (it.hasNext()) {
		Map.Entry pair = (Map.Entry) it.next();
		System.out.println(pair.getKey() + " = " + pair.getValue());
	}
}		

for Each using Key :

We can use the for-each loop to iterate over the keys, we know how do get the keys of a Map , don't you ?

Once we have the set of keys, we can using for-statement to iterate over the keys, and for every key we can retrieve the value in the map using get() method present in the Map


public static void main(String[] args) {
	Map<String, String> map = new HashMap<String, String>();
	map.put("firstKey", "firstValue");
	map.put("secndKey", "secondValue");
	map.keySet().forEach(key -> {
		System.out.println(key + " = " + map.get(key));
	});
}		

Enhanced for-Loop :

Similar to above method we can also use the enhanced for loop to iterate over the map and values.


public static void main(String[] args) {
	Map<String, String> map = new HashMap<String, String>();
	map.put("firstKey", "firstValue");
	map.put("secndKey", "secondValue");
	for(Entry entry: map.entrySet()) {
		System.out.println(entry.getKey() + " => " + entry.getValue());
	}
}	

Let me Remind you

  1. How to check if a HashMap is empty >> isEmpty()
  2. How to find the size of a HashMap >> size()
  3. How to check if a given key exists in a HashMap >> containsKey()
  4. How to check if a given value exists in a HashMap >> containsValue()
  5. How to get the value associated with a given key in the HashMap >> get()
  6. How to modify the value associated with a given key in the HashMap >> put()
  7. Remove a key from a HashMap >> remove(Object key)
  8. Remove a key from a HashMap only if it is associated with a given value >> remove(Object key, Object value)

 
Join My Facebook Group
Join Group
 

About Author

Myself KarthiQ, I am the author of this blog, I know ways to write a good article but some how I donot have the skills to make it to reach people, would you like help me to reach more people By sharing this Article in the social media.

Share this Article Facebook
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions
Copyright © CherCher Tech