Java HashMap

Java HashMap

Overview

HashMap is map based collection class that is used for storing key & value pairs which is denoted as HashMap<K, V> or HashMap<Key, Value>. It won’t maintain the order of map. It is almost similar to Hashtable except that it is unsynchronized and permits nulls. HashMap is part of java.util package

For official documentation on HashMap please refer oracle docs

Points to Remember

  • HashMap doesn’t allow duplicate keys but allows duplicate values. That means A single key can’t contain more than 1 value but more than 1 key can contain a single value.
  • HashMap allows null key also but only once and multiple null values.
  • HashMap also implements Cloneable and Serializable interface. K and V in the above definition represent Key and Value respectively.

HashMap Declaration

HashMap extends AbstractMap class and implements Map interface

public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable  

Constructors of HashMap

  • HashMap() : It will construct a default HashMap
  • HashMap(Map<? extends K,? extends V> m) : Constructs a new HashMap with the same mappings as the specified Map.
  • HashMap(int initialCapacity) : Constructs an empty HashMap with the specified initial capacity and the default load factor(0.75).
  • HashMap(int initialCapacity, float loadFactor) : Constructs an empty HashMap with the specified initial capacity and load factor.
Map<String, String> map = new HashMap<String, String>();
Map<String, Object> map1 = new HashMap<String, Object>(map);
Map<String, Object> map2 = new HashMap<String, Object>(2);
Map<String, Object> map3 = new HashMap<String, Object>(2, 3);

Methods

void clear()Used to remove all mappings from a map.
boolean containsKey(Object key)Used to return True if for a specified key, mapping is present in the map.
boolean containsValue(Object value)Used to return true if one or more key is mapped to a specified value.
Object clone()It is used to return a shallow copy of the mentioned hash map.
boolean isEmpty()Used to check whether the map is empty or not. Returns true if the map is empty.
Set entrySet()It is used to return a set view of the hash map.
Object get(Object key)It is used to retrieve or fetch the value mapped by a particular key.
Set keySet()It is used to return a set view of the keys.
int size()It is used to return the size of a map.
Object put(Object key, Object value)It is used to insert a particular mapping of key-value pair into a map.
putAll(Map M)It is used to copy all of the elements from one map into another.
Object remove(Object key)It is used to remove the values for any particular key in the Map.
Collection values()It is used to return a Collection view of the values in the HashMap.
compute(K key, BiFunction<K, V> remappingFunction)This method Attempts to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping).
computeIfAbsent(K key, Function<K> mappingFunction)This method If the specified key is not already associated with a value (or is mapped to null), attempts to compute its value using the given mapping function and enters it into this map unless null.
computeIfPresent(K key, BiFunction<K, V> remappingFunction)This method If the value for the specified key is present and non-null, attempts to compute a new mapping given the key and its current mapped value.
forEach(BiConsumer<K, V> action)This method Performs the given action for each entry in this map until all entries have been processed or the action throws an exception.
getOrDefault(Object key, V defaultValue)This method returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.
merge(K key, V value, BiFunction<K, V> remappingFunction)This method If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value.
putIfAbsent(K key, V value):This method If the specified key is not already associated with a value (or is mapped to null) associates it with the given value and returns null, else returns the current value.
replace(K key, V value)This method replaces the entry for the specified key only if it is currently mapped to some value.
replace(K key, V oldValue, V newValue)This method replaces the entry for the specified key only if currently mapped to the specified value.
replaceAll(BiFunction<K, V> function)This method replaces each entry’s value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception.

HashMap Creation

import java.util.HashMap;
import java.util.Map;

public class HashMapExample {
	public static void main(String[] args) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("Sumanth", 10);
		map.put("Vishal", 15);
		map.put("Best Selling Phone", "Nokia");
		System.out.println("Size of Map : " + map.size());
		for(String str : map.keySet()) {
			System.out.println("Key :" + str);
			System.out.println("Value :" + map.get(str).toString());
		}
	}
}
Size of Map : 3
Key :Sumanth
Value :10
Key :Vishal
Value :15
Key :Best Selling Phone
Value :Nokia

Accessing keys and modifying their associated value in a HashMap

Here in the below example we will discuss about following methods:

  • How to check if a HashMap is empty | isEmpty()
  • How to find the size of a HashMap | size()
  • How to check if a given key exists in a HashMap | containsKey()
  • How to check if a given value exists in a HashMap | containsValue()
  • How to get the value associated with a given key in the HashMap | get()
  • How to modify the value associated with a given key in the HashMap | put()
import java.util.HashMap;
import java.util.Map;

public class MethodsHashMap {
	public static void main(String[] args) {
		Map<String, String> userCityMapping = new HashMap<>();
		// Check if a HashMap is empty
		System.out.println("is userCityMapping empty? : " + userCityMapping.isEmpty());
		userCityMapping.put("Sumanth", "Hyderabad");
		userCityMapping.put("Durgesh", "Uttar Pradesh");
		userCityMapping.put("Sunil", "Rajumandry");
		System.out.println("userCityMapping HashMap : " + userCityMapping);
		// Find the size of a HashMap
		System.out.println("We have the city information of " + userCityMapping.size() + " users");
		String userName = "Sudha";
		// Check if a key exists in the HashMap
		if (userCityMapping.containsKey(userName)) {
			// Get the value assigned to a given key in the HashMap
			String city = userCityMapping.get(userName);
			System.out.println(userName + " lives in " + city);
		} else {
			System.out.println("City details not found for user " + userName);
		}
		// Check if a value exists in a HashMap
		if (userCityMapping.containsValue("Hyderabad")) {
			System.out.println("There is a user in the userCityMapping who lives in Hyderabad");
		} else {
			System.out.println("There is no user in the userCityMapping who lives in Hyderabad");
		}

		// Modify the value assigned to an existing key
		userCityMapping.put(userName, "Delhi");
		System.out.println(userName + " moved to a new city " + userCityMapping.get(userName)
				+ ", New userCityMapping : " + userCityMapping);
		// The get() method returns `null` if the specified key was not found in the
		// HashMap
		System.out.println("Sumanth's city : " + userCityMapping.get("Sumanth"));
	}
}
Output : 
is userCityMapping empty? : true
userCityMapping HashMap : {Durgesh=Uttar Pradesh, Sumanth=Hyderabad, Sunil=Rajumandry}
We have the city information of 3 users
City details not found for user Sudha
There is a user in the userCityMapping who lives in Hyderabad
Sudha moved to a new city Delhi, New userCityMapping : {Durgesh=Uttar Pradesh, Sudha=Delhi, Sumanth=Hyderabad, Sunil=Rajumandry}
Sumanth's city : Hyderabad

Remove Keys from HashMap

Here is the example that shows how to remove a key or values in HashMap

import java.util.HashMap;
import java.util.Map;

public class RemoveHashMap {
	public static void main(String[] args) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("BBC", "News");
		map.put("TV", "Entertainment");
		map.put("Mobile", "Electronics");
		map.put("Refrigerator", "Need");
		map.put("Charger", "Mobile");
		System.out.println("Original Map...");
		System.out.println(map);
		String remElement1 = map.remove("BBC");
		System.out.println("Removed Element is : " + remElement1);
		
		String remElement2 = map.remove("TV");
		System.out.println("Removed Element is : " + remElement2);
		System.out.println("Map after remove...");
		System.out.println(map);
		
		System.out.println("Removing all elements...");
		map.clear();
		System.out.println(map);
	}
}
Output : 
Original Map...
{BBC=News, TV=Entertainment, Refrigerator=Need, Charger=Mobile, Mobile=Electronics}
Removed Element is : News
Removed Element is : Entertainment
Map after remove...
{Refrigerator=Need, Charger=Mobile, Mobile=Electronics}
Removing all elements...
{}

Sorting HashMap

Sort HashMap By Key

Here is the example for sorting HashMap by their keys

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class MapSortByKey {
	public static void main(String[] args) {
		HashMap<Integer, String> map = new HashMap<Integer, String>();
		map.put(10, "AA");
		map.put(15, "CC");
		map.put(90, "ZZ");
		map.put(54, "YY");
		map.put(21, "RR");
		map.put(66, "KK");
		map.put(0, "MM");
		System.out.println("Before Sorting:");
		Set set = map.entrySet();
		Iterator iterator = set.iterator();
		System.out.println(map);
		Map<Integer, String> hmap = new TreeMap<Integer, String>(map);
		System.out.println("After Sorting:");
		Set set2 = hmap.entrySet();
		Iterator iterator2 = set2.iterator();
		while (iterator2.hasNext()) {
			Map.Entry me2 = (Map.Entry) iterator2.next();
		}
		System.out.println(hmap);
	}
}
Output:
Before Sorting:
{0=MM, 66=KK, 21=RR, 54=YY, 10=AA, 90=ZZ, 15=CC}
After Sorting:
{0=MM, 10=AA, 15=CC, 21=RR, 54=YY, 66=KK, 90=ZZ}

Sort HashMap By Value

This example shows how to sort HashMap by its values

import java.util.List;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Map;

public class MapSortByValue {
	public static void main(String[] args) {
		HashMap<String, Integer> unsortedMap = new HashMap<String, Integer>();

		// enter data into hashmap
		unsortedMap.put("Math", 98);
		unsortedMap.put("Social Studies", 85);
		unsortedMap.put("Biology", 91);
		unsortedMap.put("Physics", 95);
		unsortedMap.put("Civics", 79);
		unsortedMap.put("Geography", 80);
		System.out.println("Before Sorting Values...");
		System.out.println(unsortedMap);
		Map<String, Integer> sortedMap = sortByValue(unsortedMap);

		// print the sorted hashmap
		System.out.println("After Sorting Values...");
		System.out.println(sortedMap);
	}

	// function to sort hashmap by values
	public static HashMap<String, Integer> sortByValue(HashMap<String, Integer> hm) {
		// Create a list from elements of HashMap
		List<Map.Entry<String, Integer>> list = new LinkedList<Map.Entry<String, Integer>>(hm.entrySet());

		// Sort the list
		Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
			public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
				return (o1.getValue()).compareTo(o2.getValue());
			}
		});

		// put data from sorted list to hashmap
		HashMap<String, Integer> temp = new LinkedHashMap<String, Integer>();
		for (Map.Entry<String, Integer> aa : list) {
			temp.put(aa.getKey(), aa.getValue());
		}
		return temp;
	}
}
Output : 
Before Sorting Values...
{Geography=80, Social Studies=85, Biology=91, Civics=79, Math=98, Physics=95}
After Sorting Values...
{Civics=79, Geography=80, Social Studies=85, Biology=91, Physics=95, Math=98}

Synchronized HashMap

HashMap is a non-synchronized collection class. If we need to perform thread-safe operations on it then we must need to synchronize it explicitly.
Here is the example that briefs about synchronizing HashMap in java

Iterator should be used in a synchronized block even if we have synchronized the HashMap 

import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class SynchronizedMap {
	public static void main(String[] args) {
		Map<Integer, String> hmap= new HashMap<Integer, String>();
        hmap.put(2, "Anil");
        hmap.put(44, "Ajit");
        hmap.put(1, "Brad");
        hmap.put(4, "Sachin");
        hmap.put(88, "XYZ");
        Map map= Collections.synchronizedMap(hmap);
        Set set = map.entrySet();
        synchronized(map){
            Iterator i = set.iterator();
            // Display elements
            while(i.hasNext()) {
               Map.Entry me = (Map.Entry)i.next();
               System.out.print(me.getKey() + ": ");
               System.out.println(me.getValue());
            }
        }
	}
}
Output : 
1: Brad
2: Anil
4: Sachin
88: XYZ
44: Ajit

Conclusion

In this article, you learned what is a HashMap, how to create a HashMap, how to add new key-value pairs to a HashMap, how to remove keys from a HashMap, how to iterate over a HashMap, and how to synchronize a HashMap.

Thanks, Note

Thanks for spending your valuable time reading this post. Hope this post taught you something new today. Please share the post if you like it.

Sumanth Patnaikuni

Hi Guys. I am a technology enthusiast always try to learn new things. So I decided to share my knowledge through this platform. I worked for several companies and having 4+ years of experience. as full stack developer. Please leave your comments if there is any doubt regarding the blog. And also please recommend me if you require any particular topic so that I can guide you through my blog.

This Post Has 4 Comments

  1. turkce

    I want to voice my passion for your kind-heartedness supporting men and women that really need assistance with this one idea. Your personal dedication to getting the message across had been remarkably functional and has truly enabled guys and women much like me to realize their pursuits. Your own invaluable facts implies much to me and still more to my mates. Thank you; from everyone of us. Brigitta Maurise Rockwood

  2. turkce

    Wow! This can be one particular of the most useful blogs We have ever arrive across on this subject. Actually Magnificent. I am also an expert in this topic therefore I can understand your effort. Rickie Dav End

Leave a Reply