Home » Core Java » util » HashMap » Java Hashmap Example

About Katerina Zamani

Katerina Zamani
Katerina has graduated from the Department of Informatics and Telecommunications in National and Kapodistrian University of Athens (NKUA) and she attends MSc courses in Advanced Information Systems at the same department. Currently, her main academic interests focus on web applications, mobile development, software engineering, databases and telecommunications.

Java Hashmap Example

HashMap is a member of the Java Collection Framework and is a very common way to collect and retrieve data. HashMap represents a data structure that offers key-value pairs storing, based on hashing.

In this example we are going to show how we can create a simple HashMap and a HashMap where multiple values correspond to a key, as well as some basic functions to add and retrieve HashMap's objects.

 
 
 

1. Syntax of HashMap class

The general expression of HashMap Class is Class HashMap<K,V>, where:

  • K: specifies the type of keys maintained by this map
  • V: defines the type of mapped values

HashMap includes some different expressions for its constructor:

The arguments are:

  • initialCapacity: is the initial number of buckets of the hash table, where its default value is 16.
  • loadFactor: represents the percentage of how full the hash table can be, before the increasing of its capacity. Its default value is 0.75

2. Example of HashMap

As we mentioned we will create two different HashMaps. The first HashMap will be a simple one, so it will pair a String key with a Integer value. At the second one we want to correspond many values in to one key, so the values-argument is an ArrayList.

Create a java class named HashMapTest.java and add it into a Java project. Then, paste the following code.

HashMapTest.java:

package com.javacodegeeks.javabasics.hashmaptest;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;


public class HashMapTest {

	public static void main(String[] args) {

		// a simple hashMap declaration with default size and load factor
		HashMap<String, Integer> hashMap = new HashMap<String, Integer>();
		// hashMap with multiple values with default size and load factor
        HashMap<String, ArrayList<String>> multiMap = new HashMap<String, ArrayList<String>>();
 
        // Put elements to the hashMap
        hashMap.put("USA", new Integer(1));
        hashMap.put("UK", new Integer(2));
        hashMap.put("China",new Integer(3));

        // take a value of a specific key
        System.out.println("Simple HashMap: Key 'UK' has value = " + hashMap.get("UK"));
        
        // see if a specific value or key is into the hashMap
        System.out.println("Simple HashMap containes value '1' - " + hashMap.containsValue(1));
        System.out.println("Simple HashMap containes key 'Greece' - " 
                           + hashMap.containsKey("Greece"));
        
        // create an arrayList to store values
        ArrayList<String> listOne = new ArrayList<String>();
        listOne.add("Blue");
        listOne.add("Black");
        listOne.add("Brown");
 
        // create list two and store values
        ArrayList<String> listTwo = new ArrayList<String>();
        listTwo.add("Pink");
        listTwo.add("Purple");
        
        // put values into map
        multiMap.put("B color", listOne);
        multiMap.put("P color", listTwo);
 
        // Get a set of the entries
        Set<Entry<String, ArrayList<String>>> setMap = multiMap.entrySet();
        // Get an iterator
        Iterator<Entry<String,  ArrayList<String>>> iteratorMap = setMap.iterator();
        
        System.out.println("\nHashMap with Multiple Values");
        // display all the elements
        while(iteratorMap.hasNext()) {
        	Map.Entry<String, ArrayList<String>> entry = 
        			(Map.Entry<String, ArrayList<String>>) iteratorMap.next();
            String key = entry.getKey();
            List<String> values = entry.getValue();
            System.out.println("Key = '" + key + "' has values: " + values);
        }
        
	}

}

Lets explain the above code. As you can see, put method is called in order to add pairs of key-value in the HashMap. For multiple values, we should create an instance of an ArrayList (or a List in other occasions) and add the values in it, before putting the whole list into the HashMap. To retrieve all the elements of the HashMap we have to make a small procedure, that is based on Iterator. Firstly, we should get all the set of pairs that are contained into the HashMap, by calling entrySet() method. Then we have to get an Iterator for the entries set, in order to loop through the entire HashMap and perform operations on each key-value pair.

Moreover, we used some other methods that the class provide us in order to handle some situations easily. In order to retrieve a single value by knowing its key, get method is called, puttin the specified key as a parameter. Also to learn about an existence of a key or a value, containsKey() and containsValue() methods are used respectively. These methods return boolean value (true or false), in order to express if a key or a value exists into the map.

Now you can see the results below, in the output of the executable:

Output:

Simple HashMap: Key 'UK' has value = 2
Simple HashMap containes value '1' - true
Simple HashMap containes key 'Greece' - false

HashMap with Multiple Values
Key = 'P color' has values: [Pink, Purple]
Key = 'B color' has values: [Blue, Black, Brown]

Download the source code

This was an example of HashMap in Java. Download the source code of this example: HashMapTest.zip

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

 

Want to take your Java skills to the next level?

Grab our programming books for FREE!

Here are some of the eBooks you will get:

  • Spring Interview QnA
  • Multithreading & Concurrency QnA
  • JPA Minibook
  • JVM Troubleshooting Guide
  • Advanced Java
  • Java Interview QnA
  • Java Design Patterns