The HashMap in Java is one of the most popular Collection classes among Java programmers. After my article on How HashMap works in Java, which describes the theory part of Java HashMap and becomes hugely popular among Java programmers, I thought to share how to use HashMap in Java with essential and fundamental HashMap examples, but couldn't do that earlier and it was slipped but today we are here with all the HashMap examples about getting values to checking if a key exists in Map, I am going to share everything a Java developer should know about HashMap. The HashMap is a data structure, based on hashing, which allows you to store an object as a key-value pair, an advantage of using HashMap is that you can retrieve objects on constant time i.e. O(1) if you know the key.
The HashMap class implements a Map interface and supports Generics from Java 1.5 release, which makes it type-safe. There are a couple of more Collections, which provides similar functionalities like HashMap, which can also be used to store key-value pair.
Hashtable is one of them, but Hashtable is synchronized and performs poorly in a single-threaded environment. See Hashtable vs HashMap for complete differences between them.
Another one, relatively new is ConcurrentHashMap, which provides better performance than Hashtable in a concurrent environment and should be preferred. See the difference between ConcurrentHashMap and HashMap for detailed differences.
In this Java tutorial, we will see different examples of HashMap, like adding and removing entries, iterating over Java HashMap, checking size map, finding if a key or value exists on Map, and various other examples, which we used frequently.
The HashMap class implements a Map interface and supports Generics from Java 1.5 release, which makes it type-safe. There are a couple of more Collections, which provides similar functionalities like HashMap, which can also be used to store key-value pair.
Hashtable is one of them, but Hashtable is synchronized and performs poorly in a single-threaded environment. See Hashtable vs HashMap for complete differences between them.
Another one, relatively new is ConcurrentHashMap, which provides better performance than Hashtable in a concurrent environment and should be preferred. See the difference between ConcurrentHashMap and HashMap for detailed differences.
In this Java tutorial, we will see different examples of HashMap, like adding and removing entries, iterating over Java HashMap, checking size map, finding if a key or value exists on Map, and various other examples, which we used frequently.
Btw, if you are new to the Java Programming world then I also suggest you go through a comprehensive online Java course like The Complete Java Masterclass by Tim Buchalka on Udemy to fill the gaps in your learning because Java is vast and a structured course like this will accelerate your learning. This is also the most comprehensive (80+ hours) and most up-to-date course to learn Java in depth.
10 Java HashMap Examples for Beginners and Experienced
Before going to see these examples, few things to note about Java HashMap.It’s not synchronized, so don't share your HashMap among multiple threads.
Another common cause of the error is clearing Map and reusing it, which is perfectly valid in a single-threaded environment but if done in a multi-threaded environment can create subtle bugs.
Another common cause of the error is clearing Map and reusing it, which is perfectly valid in a single-threaded environment but if done in a multi-threaded environment can create subtle bugs.
1. How to create and add key value pair in HashMap Example
In the first example of HashMap, we will create and add an object to our Map. Always use Generics, if you are not working in Java 1.4. The following code will create HashMap with keys of type String and values of type Integer with default size and load factor.HashMap<String, Integer> cache = new HashMap<String, Integer>();
alternatively, you can create HashMap by copying data from another Map or Hashtable as shown in the below example:
Hashtable<Integer, String> source = new Hashtable<Integer,String>(); HashMap<Integer, String> map = new HashMap(source);
Adding elements is also called the put operation in HashMap and requires a key and a value object.
Here is an example of adding key and value in Java HashMap:
map.put(21, "Twenty One"); map.put(21.0, "Twenty One"); //this will throw compiler error because 21.0 is not integer
2. Retrieving value from HashMap Example
Another basic example is the retrieving value from HashMap. In order to retrieve values, we need to know the key object. let's use the key inserted in the last example, forgetting the value back from Map. get(key) method is used to get value from HashMap :Integer key = 21; String value = map.get(key); System.out.println("Key: " + key +" value: "+ value); Output: Key: 21 value: Twenty One
3. Iterating over HashMap Example
Another way to get value from HashMap is by iterating over the whole Map. Sometimes we do want to loop through the whole map and perform operations on each key-value pair, we can use Iterator for that purpose.In order to use an Iterator, we first need Set of keys, which can be retrieved using the map.keySet() method. By the way, there are multiple ways to loop through Map in Java, see here for 4 ways to loop HashMap in Java.
Here is an example of iterating over Map using java.util.Iterator :
map.put(21, "Twenty One"); map.put(31, "Thirty One"); Iterator<Integer> keySetIterator = map.keySet().iterator(); while(keySetIterator.hasNext()){ Integer key = keySetIterator.next(); System.out.println("key: " + key + " value: " + map.get(key)); } Output: key: 21 value: Twenty One key: 31 value: Thirty One
4. Size and Clear method Example in HashMap
Two fundamental examples of HashMap are finding out how many elements are stored in Map, known as the size of Map, and clearing HashMap to reuse. Java Collection API provides two convenient methods called size() and clear() to perform these operations on java.util.HashMap, here is a code example.System.out.println("Size of Map: " + map.size()); map.clear(); //clears hashmap , removes all element System.out.println("Size of Map: " + map.size()); Output: Size of Map: 2 Size of Map: 0
You can reuse Map by clearing it, but be careful if it's been shared between multiple threads without proper synchronization. Since you may need to prevent other threads from accessing the map when it's getting clear. I suggest not doing it until you have a very good reason for doing it.
5. HashMap containsKey() and containsValue() Example
In this example of Java HashMap, we will learn how to check if Map contains a particular object as a key or value. java.util.HashMap provides convenient methods like containsKey(Object key) and containsValue(Object value) which can be used for checking the existence of any key value in HashMap.Here is a code example :
System.out.println("Does HashMap contains 21 as key: " + map.containsKey(21)); System.out.println("Does HashMap contains 21 as value: " + map.containsValue(21)); System.out.println("Does HashMap contains Twenty One as value: " + map.containsValue("Twenty One")); Output: Does HashMap contains 21 as key: true Does HashMap contains 21 as value: false Does HashMap contains Twenty One as value: true
6. Checking if HashMap is empty in Java Example
In this Map example, we will learn how to check if HashMap is empty in Java. There are two ways to find out if Map is empty, one is using the size() method, if the size is zero means Map, is empty.Another way to check if HashMap is empty is using a more readable isEmpty() method which returns true if Map is empty.
Here is a code example :
boolean isEmpty = map.isEmpty(); System.out.println("Is HashMap is empty: " + isEmpty); Output: Is HashMap is empty: false
8. Removing Objects from HashMap Example
Another common example of Java HashMap is removing entries or mapping from Map. The java.util.HashMap provides the remove(Object key) method, which accepts the key and removes mapping for that key.This method returns null or the value of the entry, just removed. You can also see these Java collection courses from Pluralsight to learn more about removing or replacing existing mapping in HashMap and also learn Java collection in depth.
Anyway, here is a code example of removing key values from HashMap:
Integer key = 21; Object value = map.remove(key); System.out.println