Friday, September 22, 2023

10 Examples of HashMap in Java - Programming Tutorial

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.

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.

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);

You can also supply load factor (percentage of size, which if filled trigger resizes of HashMap) and initial capacity while creating an instance by using the overloaded constructor provided in API.

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

If you want to learn more, you can further see Java Collections: Fundamentals course by Java Champion Richard Burton, from Pluralsight to learn more about HashMap. It's a good course and available for free when you signup for a 10-day free trial.




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

See how does get() method internally works in Java to learn more about retrieving mapping in Java. The article explains how get() method uses equals() and hashCode() to retrieve value object even in case of collision.






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

You can also refer to Core Java for Impatient book by Cay S. Horstmann to learn more about iterating over Map in Java, it also covers new techniques of iteration using the forEach() method in Java 8.

10 Example of HashMap in Java




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.

Java HashMap Example | Java HashMap Tutorial



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

If you want to learn more about HashMap and Java Collections framework, I also suggest you check Java Collections from basics to Advanced courses on Udemy. It's a great course to master the Java Collection framework. 

best course to learn Java Collections




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("Following value is removed from Map: " + value);

Output:
Following value is removed from Map: Twenty One



9. Java HashMap Example- Sorting HashMap in Java

HashMap is an unsorted Map in Java, neither key nor value is sorted. If you want to sort HashMap then you can sort it based upon key or value, see how to sort HashMap on keys and values for a full code example.

Alternatively, you can use SortedMap in Java, like TreeMap. TreeMap has a constructor which accepts Map and can create a Map sorted on the natural order of key or any custom sorting order defined by Comparator.

The only thing that is key should be naturally comparable and their compareTo() method shouldn't throw an exception. Just to remind there are no Collections.sort() method defined for Map is only for List and its implementation e.g. ArrayList or LinkedList.

So any sorting for Map requires SortedMap or custom code for sorting on either key or value. here is a code example of sorting HashMap in Java by using TreeMap in the 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}

By the way, if you ever need a sorted Map then make sure you use a TreeMap not the HashMap. TreeMap will keep your data in the sorted order of key which you can also customize by providing a custom comparator in Java.


Java HashMap Examples for Beginners



10. Synchronized HashMap in Java Example

You need to synchronize HashMap if you want to use it in a multi-threaded environment. If you are running on Java 1.5 and above consider using ConcurrentHashMap in place of synchronized HashMap because it provides better concurrency.

If your project is still on JDK 1.4 then you got to use either Hashtable or synchronized Map.

The Collections.synchronizedMap(map) is used to synchronize HashMap in Java. See here for a full code example. This method returns a thread-safe version of Map and all map operation is serialized.

That's all about how to use HashMap in Java. In this article, you have learned 10 Examples of HashMap in Java which cover a lot of things from creating HashMap, adding keys and values, checking if key or value is present, whether HashMap is empty or not, and iterating over HashMap in Java. 

HashMap is an important class of Java Collection package and you will find yourself using HashMap every now and then, knowing these essential HashMap operations will help you code better in Java. 


Other Java Collection Articles you may like

Thanks for reading this article if you find these Java HashMap examples useful then please share them with your friends and colleagues. If you have any questions or feedback then please drop me a note. 

P. S. - If you are new to Java programming and looking for a free course to learn Java in a structured way then you can also check this Java Tutorial for Complete Beginners(FREE) course on Udemy. It's completely free and more than 1 million developers have joined this course. You just need a free Udemy account to join the course. 

And, now is the quiz time, what is difference between HashMap, TreeMap, and LinkedHashMap in Java? If you have to keep the keys in the sorted order which Map will you use?

21 comments:

  1. So far, it is the best intro-article on HashMaps I've ever seen. Please add some practical example of HashMap usage.

    ReplyDelete
  2. Do you know how to get all key value pair from HashMap using core Java library, without any external library? I have a requirement, where I need to convert all HashMap key values to a colon separated String e.g. key : value and send them to another system. I don't know how to convert HashMap to String, as toString() format is not the one I wanted. I have an idea to write a static method, which takes HashMap and returns a String with all key values pair separted by : and individual entries seprated by comma (,) My only problem is I don't know how to get all key values from Map?

    ReplyDelete
    Replies
    1. Hi Zavier, you can try this :

      HashMap map = new HashMap();//or your hashmap already populated
      for (Entry entry : map.entrySet()) {
      String key = entry.getKey().toString();
      String value = entry.getValue().toString();

      //do what you want with theses strings
      }

      Baptiste

      Delete
    2. write a function name gencontent build a hashmap of 10 boolean values within the looo. put hashmap value true. if loop iteration is even otherwise odd. moreover add 5 integer random valuesin the hashmapand return the hashmap object


      Pl3 brother help me in this

      Delete
  3. Very nice examples, thanks!
    Just one question, if we have the pair (21,"Twenty One") and we want to change it to (21,"Twenty Two") will the
    map.put(21, "Twenty Two"); command work?

    ReplyDelete
    Replies
    1. Ok, I read in java docs, it will.

      Delete
  4. Nice tuto mate. Much Help

    ReplyDelete
  5. I never seen this type of tutorial. good tutorial

    ReplyDelete
  6. public class HashMap {

    public static void main(String[] args) {
    java.util.HashMap map = new java.util.HashMap();
    //HashMap map = new HashMap();
    map.put(21, "Twenty One");
    Integer key = 21; String value = map.get(key);
    System.out.println("Key: " + key +" value: "+ value);

    }

    }

    Output:
    Key: 21 value: Twenty One

    ReplyDelete
  7. Nice one ... very clear and informative!

    ReplyDelete
  8. Thanks... very clear.

    ReplyDelete
  9. Thanks this article helped me a lot

    ReplyDelete
  10. hello,
    I'm doing the java program that connects to the mysql databse.
    there are four different tables in my database and i'm writing the four class respectively.
    the problem is that,
    i want to store my data retrieved from database table into the HashMap collection. and print the data of the Collection.
    Can Anyone tell how can i do this?

    ReplyDelete
  11. in any table u will have one unique key definitely,so take dat as key and object returned from database as value...map

    ReplyDelete
  12. I have to retrieve key from value in hashmap.
    i have input both key and value from main method.Then i input value to retrieve the corresponding key for that value
    i am passing value as a parameter in a method.

    my output returns NULL. Please help me get the correct output.

    public String findDomainName(String ipAddress)
    {
    String domain = null;
    for (Map.Entry entry : domainMap.entrySet())
    {
    String k = entry.getKey();
    String v = ipAddress;

    if (k.equals(v)) {
    domain = k;

    }

    }

    return domain;

    }

    ReplyDelete
  13. How can i use multiple values with hashMp

    ReplyDelete
    Replies
    1. You can store a Collection like ArrayList or LinkedList as value in HashMap and there you can store more than one values, or you can use MultiMap from Google Guava or similar class from other open source collection libraries.

      Delete
  14. I need ans of this question ASAP
    write a function name gencontent build a hashmap of 10 boolean values within the looo. put hashmap value true. if loop iteration is even otherwise odd. moreover add 5 integer random valuesin the hashmapand return the hashmap object

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.