Hashmap Java Example (with video) (original) (raw)

Java 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. HashMap Methods provided, allow you to add, modify and remove elements when needed.

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.

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.

You can also check this tutorial in the following video:

HashMap Java Example – Video

1. Syntax of the HashMap Java class

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

HashMap includes some different expressions for its constructor:

The arguments are:

2. Properties of HashMap

3. Hashmap in Collection hierarchy

HashMap class extends AbstractMap class and implements Map interface. As shown in the following figure-

Hashmap Java - Hashmap in Collection hierarchy

Hashmap in Collection hierarchy

4. Important methods in Java HashMap

Following are the method present in java.util.HashMap class-

  1. clear(): Removes all of the mappings from this map.
  2. clone(): Returns a shallow copy of this HashMap instance: the keys and values themselves are not cloned.
  3. compute(K key, BiFunction remappingFunction): Attempts to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping).
  4. computeIfAbsent(K key, Function mappingfunction): 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.
  5. computeIfPresent(K key, BiFunction remappingfunction): 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.
  6. containsKey(Object key): Returns true if this map contains a mapping for the specified key.
  7. containsValue(Object value): Returns true if this map maps one or more keys to the specified value.
  8. entrySet(): Returns a Set view of the mappings contained in this map.
  9. forEach(): Performs the given action for each entry in this map until all entries have been processed or the action throws an exception.
  10. get(Object key): Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
  11. getOrDefault(Object key, V defaultValue): Returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.
  12. isEmpty(): Returns true if this map contains no key-value mappings.
  13. keySet(): Returns a Set view of the keys contained in this map.
  14. merge(K key, V value, BiFunction remapping Function): If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value.
  15. put(K key, V value): Associates the specified value with the specified key in this map.
  16. putAll(Map m): Copies all of the mappings from the specified map to this map.
  17. putIfAbsent(K key, V value): 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.
  18. remove(Object key): Removes the mapping for the specified key from this map if present.
  19. remove(Object key, Object value): Removes the entry for the specified key only if it is currently mapped to the specified value.
  20. replace(K key, V value): Replaces the entry for the specified key only if it is currently mapped to some value.
  21. replace(K key, V oldValue, V newValue): Replaces the entry for the specified key only if currently mapped to the specified value.
  22. replaceAll(BiFunction function): 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.
  23. size(): Returns the number of key-value mappings in this map.
  24. values(): Returns a Collection view of the values contained in this map.

4.1 compute(), computeIfAbsent() and computeIfPresent() methods in Java HashMap

Compute Method Demo

HashMap<Integer, String> nameMap = new HashMap(); nameMap.put(1, "John"); nameMap.put(2, "Jack");

System.out.println("Initial map: " + nameMap);

nameMap.compute(1, (key, val) -> val.concat(" Smith")); System.out.println("Map after re evaluating the value for key 1: " + nameMap); // will throw NullPointerException because key is not present //nameMap.compute(3, (key, val) -> val.concat(" Smith"));

//Since key 4 is not present it will get inserted with key 4 and value Steve nameMap.computeIfAbsent(4, key -> "Steve"); System.out.println("Map after re evaluating the value for key 4 if it is absent: " + nameMap); //Since key 1 is present it will not get inserted nameMap.computeIfAbsent(1, key -> "Steve"); System.out.println("Map after re evaluating the value for key 1 if it is absent: " + nameMap);

//Since key 4 is present its value will get calculated as per mapping function nameMap.computeIfPresent(4, (key, val) -> val.concat(" Smith")); System.out.println("Map after re evaluating the value for key 1 if it is Present: " + nameMap); //Since key 5 is not present so its value will not get calculated nameMap.computeIfPresent(5, (key, val) -> val.concat(" Smith")); System.out.println("Map after re evaluating the value for key 1 if it is Present: " + nameMap);

Explanation:

Now let’s see the output:

Result

Initial map: {1=John, 2=Jack} Map after re evaluating the value for key 1: {1=John Smith, 2=Jack} Map after re evaluating the value for key 4 if it is absent: {1=John Smith, 2=Jack, 4=Steve} Map after re evaluating the value for key 1 if it is absent: {1=John Smith, 2=Jack, 4=Steve} Map after re evaluating the value for key 1 if it is Present: {1=John Smith, 2=Jack, 4=Steve Smith} Map after re evaluating the value for key 1 if it is Present: {1=John Smith, 2=Jack, 4=Steve Smith}

4.2 containsKey() and containsValue() method in Java HashMap

Contains Method Demo

HashMap<Integer, String> nameMap = new HashMap(); nameMap.put(1, "John"); nameMap.put(2, "Jack"); //returns true because key 1 is present in map System.out.println("Is key 1 present in map(" + nameMap + "? : " + nameMap.containsKey(1)); //returns false because key 3 is not present in map System.out.println("Is key 3 present in map(" + nameMap + "? : " + nameMap.containsKey(3));

//returns true because value John is present in map System.out.println("Is value John present in map(" + nameMap + "? : " + nameMap.containsValue("John")); //returns false because value Steve is not present in map System.out.println("Is value Steve present in map(" + nameMap + "? : " + nameMap.containsValue("Steve"));

Explanation:

Result

Is key 1 present in map({1=John, 2=Jack}? : true Is key 3 present in map({1=John, 2=Jack}? : false Is value John present in map({1=John, 2=Jack}? : true Is value Steve present in map({1=John, 2=Jack}? : false

4.3 get() and getOrDefault() method in Java HashMap

Get Method Demo

HashMap<Integer, String> nameMap = new HashMap(); nameMap.put(1, "John"); nameMap.put(2, "Jack");

//Since value for key 1 is present in map so get() returns its value System.out.println("value for key 1 in map(" + nameMap + " is : " + nameMap.get(1)); //Since value for key 3 is not present in map so get() returns null System.out.println("value for key 3 in map(" + nameMap + " is : " + nameMap.get(3));

//Since value for key 1 is present in map so getOrDefault() returns its value System.out.println("value for key 1 in map(" + nameMap + " is present in map and value is: " + nameMap.getOrDefault(1, "Steve")); //Since value for key 1 is present in map so getOrDefault() returns default value System.out.println("value for key 3 in map(" + nameMap + " is not present so default value is: " + nameMap.getOrDefault(3, "Steve"));

Explanation:

Result

value for key 1 in map({1=John, 2=Jack} is : John value for key 3 in map({1=John, 2=Jack} is : null value for key 1 in map({1=John, 2=Jack} is present in map and value is: John value for key 3 in map({1=John, 2=Jack} is not present so default value is: Steve

4.4 put(), putIfAbsent() and putAll() method in Java HashMap

Put Method Demo

HashMap<Integer, String> nameMap = new HashMap(); nameMap.put(1, "John");

System.out.println("Initial map: " + nameMap);

System.out.println("Adding element key 2 and value Jack"); nameMap.put(2, "Jack"); System.out.println("Updated map: " + nameMap);

System.out.println("Adding element key 2 and value Jack1 if key 2 is absent"); nameMap.putIfAbsent(2, "Jack"); System.out.println("Updated map: " + nameMap);

System.out.println("Adding element key 3 and value Steve if key 2 is absent"); nameMap.putIfAbsent(3, "Steve"); System.out.println("Updated map: " + nameMap);

HashMap anotherNameMap = new HashMap(); anotherNameMap.put(4, "Alex");

System.out.println("Adding map "+ anotherNameMap+" to map "+nameMap); nameMap.putAll(anotherNameMap);

System.out.println("Updated map: " + nameMap);

Explanation:

Now let’s have a look over the output of the above code-

Result

Initial map: {1=John} Adding element key 2 and value Jack Updated map: {1=John, 2=Jack} Adding element key 2 and value Jack1 if key 2 is absent Updated map: {1=John, 2=Jack} Adding element key 3 and value Steve if key 2 is absent Updated map: {1=John, 2=Jack, 3=Steve} Adding map {4=Alex} to map {1=John, 2=Jack, 3=Steve} Updated map: {1=John, 2=Jack, 3=Steve, 4=Alex}

4.5 remove() in Java HashMap

Remove Method Demo

HashMap<Integer, String> nameMap = new HashMap(); nameMap.put(1, "John"); nameMap.put(2, "Jack"); nameMap.put(3, "Steve"); nameMap.put(4, "Alex"); System.out.println("Initial map: " + nameMap);

System.out.println("Removing entry with key 1"); nameMap.remove(1); System.out.println("Updated map: " + nameMap);

//Since no key value pair matches no action will be taken System.out.println("Removing entry with key 3 and value Steve1"); nameMap.remove(3, "Steve1"); System.out.println("Updated map: " + nameMap);

//Since key value pair matches it will remove corresponding entry from map System.out.println("Removing entry with key 3 and value Steve"); nameMap.remove(3, "Steve"); System.out.println("Updated map: " + nameMap);

Explanation:

Result

Initial map: {1=John, 2=Jack, 3=Steve, 4=Alex} Removing entry with key 1 Updated map: {2=Jack, 3=Steve, 4=Alex} Removing entry with key 3 and value Steve1 Updated map: {2=Jack, 3=Steve, 4=Alex} Removing entry with key 3 and value Steve Updated map: {2=Jack, 4=Alex}

4.6 replace() and replaceAll() method in Java HashMap

Replace Method Demo

HashMap<Integer, String> nameMap = new HashMap(); nameMap.put(1, "John"); nameMap.put(2, "Jack"); System.out.println("Initial map: " + nameMap);

System.out.println("Replacing value of entry with key 1 with Steve in map: " + nameMap); nameMap.replace(1, "Steve"); System.out.println("Updated map: " + nameMap);

System.out.println("Replacing value of entry with key 1 value Steve with John in map: " + nameMap); nameMap.replace(1, "Steve", "John"); System.out.println("Updated map: " + nameMap);

System.out.println("Replacing value of entry with key 1 value John1 with John in map: " + nameMap); nameMap.replace(1, "John1", "Steve"); System.out.println("Updated map: " + nameMap);

System.out.println("Replacing value of all entries original value plus "Smith": " + nameMap); nameMap.replaceAll((key, val) -> val.concat(" Smith")); System.out.println("Updated map: " + nameMap);

Explanation:

Result

Initial map: {1=John, 2=Jack} Replacing value of entry with key 1 with Steve in map: {1=John, 2=Jack} Updated map: {1=Steve, 2=Jack} Replacing value of entry with key 1 value Steve with John in map: {1=Steve, 2=Jack} Updated map: {1=John, 2=Jack} Replacing value of entry with key 1 value John1 with John in map: {1=John, 2=Jack} Updated map: {1=John, 2=Jack} Replacing value of all entries original value plus "Smith": {1=John, 2=Jack} Updated map: {1=John Smith, 2=Jack Smith}

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 into 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 hashMap = new HashMap();
    // hashMap with multiple values with default size and load factor
    HashMap<String, ArrayList> multiMap = new HashMap<String, ArrayList>();

    // 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 contains value '1' - " + hashMap.containsValue(1));
    System.out.println("Simple HashMap contains key 'Greece' - "
    + hashMap.containsKey("Greece"));

    // create an arrayList to store values
    ArrayList listOne = new ArrayList();
    listOne.add("Blue");
    listOne.add("Black");
    listOne.add("Brown");

    // create list two and store values
    ArrayList listTwo = new ArrayList();
    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>> setMap = multiMap.entrySet();
    // Get an iterator
    Iterator<Entry<String, ArrayList>> iteratorMap = setMap.iterator();

    System.out.println("\nHashMap with Multiple Values");
    // display all the elements
    while(iteratorMap.hasNext()) {
        Map.Entry<String, ArrayList> entry = 
        (Map.Entry<String, ArrayList>) iteratorMap.next();
        String key = entry.getKey();
        List values = entry.getValue();
        System.out.println("Key = '" + key + "' has values: " + values);
    }

}

}

Output

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

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

Let’s 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 sets 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 the method is called, putting the specified key as a parameter. Also to learn about the existence of a key or a value, containsKey() and containsValue()methods are used respectively. These methods return a boolean value (true or false), in order to express if a key or a value exists in the map.

6. Different ways to iterate Java HashMap

There are many ways to iterate over HashMap in java. Let’s see each method in detail-

Iterating Map

HashMap nameMap = new HashMap(); nameMap.put(1, "John"); nameMap.put(2, "Jack");

System.out.println("Iterating by using Entry and entrySet()");

for (Map.Entry entry : nameMap.entrySet()) System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());

System.out.println("Iterating over keys using For-Each loop"); for (Integer key : nameMap.keySet()) System.out.println("Key = " + key + ", Value = " + nameMap.get(key));

System.out.println("Iterating over values using For-Each loop"); for (String value : nameMap.values()) System.out.println("Value = " + value);

System.out.println("Iterating using Iterator"); Iterator<Map.Entry> entries = nameMap.entrySet().iterator(); while (entries.hasNext()) { Map.Entry entry = entries.next(); System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); }

System.out.println("Iterating over keys and searching for values"); for (Integer key : nameMap.keySet()) { String value = nameMap.get(key); System.out.println("Key = " + key + ", Value = " + value); }

System.out.println("Iterating by java8 foreach"); nameMap.forEach((k,v)->System.out.println("Item : " + k + " Count : " + v));

Result

Iterating by using Entry and entrySet() Key = 1, Value = John Key = 2, Value = Jack Iterating over keys using For-Each loop Key = 1, Value = John Key = 2, Value = Jack Iterating over values using For-Each loop Value = John Value = Jack Iterating using Iterator Key = 1, Value = John Key = 2, Value = Jack Iterating over keys and searching for values Key = 1, Value = John Key = 2, Value = Jack Iterating by java8 foreach Item : 1 Count : John Item : 2 Count : Jack

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

8. Download the Source Code

This was an example of HashMap in Java.

Download
You can download the full source code of this example here: HashMap Java Example

Last updated on Jan. 17th, 2022