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 . Java 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 value . Hashmap in java 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).

Java HashMap Hierarchy

HashMap Java 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

Java HashMap Features

Hashmap java have some specific characteristics as below .

  1. Java HashMap contains only unique keys.
  2. HashMap in Java may have multiple null values but only one null key.
  3. HashMap Java 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 In java implements Cloneable and Serializable interfaces.
  7. If  try to add duplicate key , it will update value of key in hashmap.

Create hashmap java

Now we will discuss different methods to initialize  hashmap in java .  We can create hashmap java  using these Constructor
HashMap() – Constructs an empty  Java HashMap with the default initial capacity (16) and the default load factor (0.75).
HashMap(int initialCapacity) – Constructs an empty HashMap in java with the specified initial capacity and the default load factor (0.75).
HashMap(int initialCapacity, float loadFactor) – Constructs an empty Java 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. This is a methods to create map with values in java .
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}

In this java hashmap example we have initialized hashmap in java using constructor and then put element in map . for more details see create hashmap java with examples .

How to iterate hashmap in java

We can iterate hashmap in java using entrySet , keyset with the help of  for each loop or  java Iterator . Let’s see how java iterating hashmap and get keys-values pairs in following java hashmap example .

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
In this java hashmap example we have learned how to iterate hashmap in java . You can learn iterate map in java in details .

Hashmap methods in java

Now we will discuss various hashmap methods in java .  Hashmap in java have inbuild methods, these hashmap java methods are easy to use and make developer work easy . You should once reads about java map methods as following .

  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

Java hashmap example

Now we will see nice java hashmap example collection . These java map example are well explained with simple java programs .

In this tutorial you learned what is java hashmap , create hashmap java and how to iterate hashmap in java and various hashmap methods in java .
References :

Leave a Reply

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

+ 78 = 82