HashMap in
Java is one of the most popular Collection class among Java programmers. After by article
How HashMap works in Java, which describes theory part of
Java HashMap ,I thought to share, How to use HashMap in Java with fundamental HashMap examples, but couldn't do that and it was slipped. HashMap is a a data structure, based on hashing, which allows you to store object as key value pair, advantage of using HashMap is that, you can retrieve object on constant time i.e. O(1), if you know the key. HashMap implements Map interface and supports
Generics from Java 1.5 release, which makes it type safe. There are 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 poor in 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 concurrent environment and should be preferred. See
difference between ConcurrentHashMap and HashMap for detail 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.
Java HashMap Example
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 error is clearing Map and reusing it, which is perfectly valid in single threaded environment but if done in multi-threaded environment can create subtle bugs.
Java HashMap Example 1: Create and add objects in HashMap
In first example of HashMap, we will create and add object into our Map. Always use Generics, if you are not working in Java 1.4. 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 from copying data from another Map or
Hashtable as shown in below example:
Hashtable<Integer, String> source = new Hashtable<Integer,String>();HashMap<Integer, String> map = new HashMap(source);
You can also supply load factor (percentage of size, which if fulled trigger resize of HashMap) and initialiCapacity while creating instance by using overloaded constructor provided in API. Adding elements, also called put operation, requires key and 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
Java HashMap Example 2: Retrieving value from HashMap
Another basic example is retrieving value from HashMap. in order to retrieve values, we need to know key object. let's use the key inserted in last example, for getting value back from Map. get(key) method is used to get value form HashMap :
Integer key = 21;String value = map.get(key);System.out.println("Key: " + key +" value: "+ value); Output: Key: 21 value: Twenty One
Java HashMap Example 3: Iterating over HashMap
Another way to get value from HashMap is by iterating over whole Map. Sometime we do want to loop through whole map and perform operations on each key value pair, we can use Iterator for that purpose. In order to use Iterator, we first need Set of keys, which can be retrieved using 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 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 Onekey: 31 value: Thirty One
Java HashMap Example 4: Size and Clear in HashMap
Two fundamental example of HashMap, is finding out how many elements are stored in Map, known as size of Map and clearing HashMap to reuse. Java Collection API provides two convinient method called size() and clear() to perform these operation on java.util.HashMap, here is code example.
System.out.println("Size of Map: " + map.size());map.clear(); //clears hashmap , removes all elementSystem.out.println("Size of Map: " + map.size()); Output:Size of Map: 2Size of Map: 0
You can reuse Map by clearing it, but be careful if its been shared between multiple threads without proper
synchronization. Since you may need to prevent other thread from accessing map when its getting clear. I suggest not to do, until you have very good reason of doing it.
Java HashMap Example 5 and 6: ContainsKey and ContainsValue Example
In this example of Java HashMap, we will learn how to check if Map contains a particular object as key or value. java.util.HashMap provides convenient methods like containsKey(Object key) and containsValue(Object value) which can be used to for checking existence of any key value in HashMap. here is 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: trueDoes HashMap contains 21 as value: falseDoes HashMap contains Twenty One as value: true
Java HashMap Example 7: Checking if HashMap is empty
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 size() method, if size is zero means Map is empty. Another way to
check if HashMap is empty is using more readable isEmpty() method which returns true if Map is empty. Here is code example:
boolean isEmpty = map.isEmpty();System.out.println("Is HashMap is empty: " + isEmpty);Output:Is HashMap is empty: false
Java HashMap Example 8: Removing Objects from HashMap
Another
common example of Java HashMap is removing entries or mapping from Map. Java.util.HashMap provides remove(Object key) method, which accept key and removes mapping for that key.This method, returns null or the value of entry, just removed. Here is a code example of removing key value from HashMap:
Integer key = 21;Object value = map.remove(key);System.out.println("Following value is removed from Map: " + value);Output:Following value is removed from Map: Twenty One
Java HashMap Example 9: Sorting HashMap in Java
HashMap is an unsorted Map in Java, neither key or value is sorted. If you want to sort HashMap than you can sort it based upon key or value, see
how to sort HashMap on keys and values for full code example. Alternatively, you can use SortedMap in Java like TreeMap. TreeMap has constructor which accepts Map and can create a Map sorted on natural order of key or any custom sorting order defined by
Comparator. Only thing is key should be naturally comparable and there
compareTo() method shouldn't throw exception. Just to remind there is no Collections.sort() method defined for Map is only for List and it’s implementation e.g.
ArrayList or LinkedList. So any sorting for Map require SortedMap or custom code for sorting on either key or value. here is code example of sorting HashMap in Java by using
TreeMap in natural order of keys:
map.put(21, "Twenty One");map.put(31, "Thirty One");map.put(41, "Thirty One");System.out.println("Unsorted HashMap: " + map);TreeMap sortedHashMap = new TreeMap(map); System.out.println("Sorted HashMap: " + sortedHashMap); Output:Unsorted HashMap: {21=Twenty One, 41=Thirty One, 31=Thirty One}Sorted HashMap: {21=Twenty One, 31=Thirty One, 41=Thirty One}
Java HashMap Example 10: Synchronized HashMap in Java
You need to synchronize HashMap if you want to use it in multi-threaded environment. If you are running on Java 1.5 and above consider using ConcurrentHashMap in place of synchronized HashMap because it provide better concurrency. If your project is still on JDK 1.4 than you got to use either Hashtable or synchronized Map. Collections.synchronizedMap(map) is used to synchronize HashMap in Java. See
here for full code example. This method returns a thread-safe version of Map and all map operation is serialized.