Java HashMap Examples

Java HashMap Class implements the Map interface that is used for storing Key & value pairs , where keys should be unique and values can be duplicate.Javaa HashMap allows to store the null elements,but there should be only one null key.It is denoted as HashMap<K,V>, where K stands for key and V for  valueJava HashmMap Class is not an ordered collection which means it does not return the keys and values in the same order in which they have been inserted into the HashMap. HashMap class is similar to the Hashtable class except that it is unsynchronized and permits nulls(null values and null key).
HashMap has two parameters that affect its performance one initial capacity and second load factor.
The initial default capacity of Java HashMap class is 16 with a load factor of 0.75.The capacity is the number of buckets in the hash table, and the initial capacity is capacity at the time the hash table is created. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. Whenever the number of entries in the hash table exceeds the product of the load factor and the current capacity, the hash table is rehashed (that is, internal data structures are rebuilt) so that now the hash table has approximately twice the number of buckets.

HashMap Hierarchy

Java HashMap Class implements Map interface and extends AbstractMap class.Declaration Of HashMap Class As Below.
public class HashMap<K,V> extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable {


//More Code

}
java hashmap class hierarchy
                                         java hashmap class hierarchy

HashMap Features

  1. HashMap contains only unique keys.
  2. HashMap may have multiple null values but only one null key.
  3. HashMap is an unordered collection.It does not give any guarantee of specific order of the elements.
  4. Java HashMap is non-synchronize so it is not thread-safe. You must explicitly synchronize concurrent modifications to the HashMap as
    Map m = Collections.synchronizedMap(new HashMap(…));
  5. The initial default capacity of Java HashMap is 16 and load factor is 0.75.
  6. HashMap implements Cloneable and Serializable interfaces.
  7. If  try to add duplicate key , it will update value of key in hashmap.

Creating HashMap And Adding elements to it

We can create hashmap using these Constructor
HashMap() – Constructs an empty HashMap with the default initial capacity (16) and the default load factor (0.75).
HashMap(int initialCapacity) – Constructs an empty HashMap with the specified initial capacity and the default load factor (0.75).
HashMap(int initialCapacity, float loadFactor) – Constructs an empty HashMap with the specified initial capacity and load factor.
HashMap(Map<? extends K,? extends V> m) – Constructs a new HashMap with the same mappings as the specified Map.
We can add new element means key and value pair using put() method in hashmap. Let’s see this by code.
package com.demo;

import java.util.HashMap;
import java.util.Map;

public class HashMapExample {
	
	public static void main(String[] args) {
		
		/*
		 *Constructs an empty HashMap with the default initial capacity (16) 
		 *and the default load factor (0.75).
		 */
		Map<String, String> hashMap = new HashMap<String, String>();
		
		/*
		 *Associates the specified value with the specified key in
                   this map (optional operation). If the map previously 
                   contained a mapping for the key, the old value is replaced
                   by thespecified value.(A map m is said to contain a 
                   mapping for a key k if and only if m.containsKey(k)
                   would return true.)
		 */
		hashMap.put("hcl", "amit");
		hashMap.put("tcs","ravi");
		hashMap.put("wipro","anmol");
		
		//display the element of hashmap
		System.out.println("element in hashmap ="+ hashMap);
		
	}

}

Output :

element in hashmap ={hcl=amit, tcs=ravi, wipro=anmol}

Iterate a HashMap

We have different ways of iterating over a HashMap as following –

  • Iterating  the HashMap using entrySet.
  • Iterating the HashMap  using simple for-each loop..
Let’s see these things by code.
package com.demo;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class HashMapExample {
	
	public static void main(String[] args) {
		
		/*
		 *Constructs an empty HashMap with the default initial capacity (16) 
		 *and the default load factor (0.75).
		 */
		Map<String, String> hashMap = new HashMap<String, String>();
		
		/*
		 *Associates the specified value with the specified 
		 *key in this map (optional operation). 
		 *If the map previously contained a mapping for the key,
		 * the old value is replaced by the specified value. 
		 *(A map m is said to contain a mapping for a key k
		 * if and only if m.containsKey(k) would return true.)
		 */
		hashMap.put("hcl", "amit");
		hashMap.put("tcs","ravi");
		hashMap.put("wipro","anmol");
		
System.out.println("====>> Iterating  HashMap using entrySet ===>>");
 Set<Map.Entry<String, String>> employeeEntries = hashMap.entrySet();
    Iterator<Map.Entry<String, String>> employeeIterator = employeeEntries.iterator();
        while (employeeIterator.hasNext()) {
            Map.Entry<String, String> entry = employeeIterator.next();
           System.out.println("Key Of map = "+ entry.getKey() + " , 
                       value of map = " + entry.getValue() );
        }

        System.out.println("===>> Iterating  HashMap using for-each loop ===>>");
        for(Map.Entry<String, String> entry: hashMap.entrySet()) {
            System.out.println("Key Of map = "+ entry.getKey() 
                 + " , value of map = " + entry.getValue() );
        }
        
		
	}

}
Output :
====>> Iterating  HashMap using entrySet ===>>
Key Of map = hcl , value of map = amit
Key Of map = tcs , value of map = ravi
Key Of map = wipro , value of map = anmol
===>> Iterating  HashMap using entrySet with simple for-each loop ===>>
Key Of map = hcl , value of map = amit
Key Of map = tcs , value of map = ravi
Key Of map = wipro , value of map = anmol

HashMap Methods

  1. void clear() – It removes all of the mappings from this map.
  2. Object clone() – it rreturns a shallow copy of this HashMap instance: the keys and values themselves are not cloned.
  3. boolean containsKey(Object key) – It returns true if this map contains a mapping for the given key.
  4. boolean containsValue(Object value) – it returns true if this map maps one or more keys to the given value.
  5. Set<Map.Entry<K,V>> entrySet() – It returns a Set view of the mappings contained in this map.
  6. V get(Object key) – It returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
  7. V getOrDefault(Object key, V defaultValue) – It returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.
  8. boolean isEmpty() – It returns true if this map contains no key-value mappings.
  9. Set<K> keySet() – It returns a Set view of the keys contained in this map.
  10. V merge(K key, V value, BiFunction<? super V,? super V,? extends V> remappingFunction) – If the given key is not already associated with a value or is associated with null, associates it with the given non-null value.
  11. V put(K key, V value) – it associates the given value with the givenkey in this map.
  12. V remove(Object key) – it removes the mapping for the given key from this map if present.
  13. boolean remove(Object key, Object value) – It Removes the entry for the given key only if it is currently mapped to the given value.
  14. V replace(K key, V value) – It replaces the entry for the specified key only if it is currently mapped to some value.
  15. boolean replace(K key, V oldValue, V newValue) – It replaces the entry for the specified key only if currently mapped to the specified value.
  16. int size() – It returns the number of key-value mappings in this map.
  17. Collection<V> values() – It returns a Collection view of the values contained in this map.

HashMap tutorials and examples

References :

Leave a Reply

Your email address will not be published. Required fields are marked *

64 − = 58