HashMap in Java

HashMap in Java

HashMap implements Map and extends AbstractMap.  It does not add any methods of its own. It is most common class used and its implementation is based on Hashtable. You can find different ways to iterate a HashMap in our tutorial how to iterate a Map in Java.

Listed below are the features of HashMap.

  1. It stores key-value pairs.
  2. It contains unique key.
  3. HashMap allows one null key and multiple null values.
  4. Insertion order is not maintain in HashMap.
  5. HashMap allows the execution time of basic operations, such as get( ) and put( ), to remain constant even for large sets.

HashMap provides following constructors.

HashMap()Default construtor.
HashMap(Map m)Creates object of the HashMap by using the elements of m.
HashMap(int capacity)Creates object of HashMap with initial capacity.
HashMap(int capacity, float fillRatio)Creates object of HashMapwith initial capacity and fillRatio. The fill ratio must be between 0.0 and 1.0.

Load Factor/Fill Ratio

Load Factor determines how full the HashMap can be before it is resized upward. when the number of elements is greater than the capacity of the HashMap multiplied by its load factor/fill ratio, the HashMap is expanded. Default value of load factor is 0.75.

package com.code2succeed.collection;

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

public class HashMapExample {
	public static void main(String[] args) {
		HashMap<Integer, String> map = new HashMap<Integer, String>();
		map.put(1, "New York");
		map.put(2, "London");
		map.put(3, "Paris");
		map.put(4, "Mumbai");
		//Iterate HashMap using iterator
		Iterator<Entry<Integer, String>> iterator = map.entrySet().iterator();
		System.out.println("Using Iterator");
		while (iterator.hasNext()) {
			Map.Entry<Integer,String> entry = (Map.Entry<Integer,String>) iterator.next();
			System.out.println("Key : " + entry.getKey() + " Value :" + entry.getValue());
		//Iterate using keySet
		System.out.println("Iterate using keySet");
		for (Object key : map.keySet()) {
			System.out.println("Key : " + key + " Value : " + map.get(key));

Output :

Using Iterator
Key : 1 Value :New York
Key : 2 Value :London
Key : 3 Value :Paris
Key : 4 Value :Mumbai
Iterate using keySet
Key : 1 Value : New York
Key : 2 Value : London
Key : 3 Value : Paris
Key : 4 Value : Mumbai

Leave a Reply

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