HashMap in Java With Example

Here we will see HashMap in Java With Example.

Basic Points about HashMap in Java.

HashMap is used to store the element in the form of key and value format.
HashMap, the key cannot be duplicate key, the value can be duplicate.
HashMap can have a null as key or value.
HashMap stores the elements in an unordered way.
The HashMap element can be accessed randomly.
Hashmap none of the methods are synchronized so the HashMap class is also not synchronized.
HashMap objects are eligible for Serialization and Cloning.
HashMap element can’t be accessed by using Enumeration and ListIterator directly.
HashMap class extends AbstractMap class and implements Map, Cloneable, Serializable interface.

In order to access the elements of HashMap, we can access on the basis of values or on the basis of the key. Let’s see an example.

package javatute.hashmap;

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

class HashMapExample {
	public static void main(String[] arg) {
		Map<Integer, String> hashmapObject = new HashMap<>();

		hashmapObject.put(2, "ram");
		hashmapObject.put(3, "mohan");
		hashmapObject.put(4, "Bangalore");
		hashmapObject.put(5, "Rakesh");

		// we will iterate using Iterator
		Iterator<Map.Entry<Integer, String>> iterator = hashmapObject
				.entrySet().iterator();

		while (iterator.hasNext()) {
			Map.Entry<Integer, String> entry = iterator.next();
			System.out.println("Key is = " + entry.getKey() + ", Value is = "
					+ entry.getValue());
		}
	}
}

Output is –

Key is = 2, Value is = ram
Key is = 3, Value is = mohan
Key is = 4, Value is = Bangalore
Key is = 5, Value is = Rakesh

 

Sort HashMap on the basis of the key with example.

We can sort HashMap on the basis of the key after converting it into TreeMap.

Let’s see an example of Sort HashMap by key in java.

package sortingmapbasisofkey;
import java.util.*;
public class SortHashMapBasisOfKey {
public static void main(String[] args) {
	
	
	Map<Integer, String> hashMapObj = new HashMap<>();	 
	hashMapObj.put(2, "ram");
	hashMapObj.put(5, "mohan");
	hashMapObj.put(3, "sohan");
	hashMapObj.put(9, "rohit");
	hashMapObj.put(22, "rahul");
	hashMapObj.put(1, "aman");
	System.out.println("before sorting --------");
	for (Integer key : hashMapObj.keySet()) {
		System.out.println("Key is : " + key + "   Value is : " + hashMapObj.get(key));
	}
	
	//We will convert HashMap into TreeMap, We have TreeMap constructor which can have hashMap object
	Map<Integer, String> treeMapObj = new TreeMap<Integer, String>(hashMapObj); 
	System.out.println("After sorting --------");
	for (Integer key : treeMapObj.keySet()) {
		System.out.println("Key is : " + key + "   Value is : " + treeMapObj.get(key));
	}
}
}

Output is –

before sorting ——–
Key is : 1 Value is : aman
Key is : 2 Value is : ram
Key is : 3 Value is : sohan
Key is : 5 Value is : mohan
Key is : 22 Value is : rahul
Key is : 9 Value is : rohit
After sorting ——–
Key is : 1 Value is : aman
Key is : 2 Value is : ram
Key is : 3 Value is : sohan
Key is : 5 Value is : mohan
Key is : 9 Value is : rohit
Key is : 22 Value is : rahul

 

Sort HashMap on the basis of the Value with example.

We can sort HashMap on basis of value using the Comparator interface.

package sortinghashmapbyvalue;

import java.util.*;


public class SortHashMapBasisOfValue {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
	Map<Integer, String> hashMapObj = new HashMap<>();
	 
	hashMapObj.put(2, "ram");
	hashMapObj.put(5, "mohan");
	hashMapObj.put(3, "sohan");
	hashMapObj.put(9, "rohit");
	hashMapObj.put(22, "rahul");
	hashMapObj.put(1, "aman");
	System.out.println("before sorting by value--------");
	for (Integer key : hashMapObj.keySet()) {
		System.out.println("Key is : " + key + "   Value is : " + hashMapObj.get(key));
	}		
	
	List<Integer> listObject = new ArrayList(hashMapObj.entrySet());
	// Define anonymous inner class	

    Collections.sort(listObject, new Comparator() {
         
    	// Override compare() method and define custom logic
		public int compare(Object o1, Object o2) {
			
			//downcast o1 to Map.Entry<Integer, String> and assign new reference variable
			Map.Entry<Integer, String> object1 = (Map.Entry<Integer, String>)o1;
			Map.Entry<Integer, String> object2 = (Map.Entry<Integer, String>)o2;
			
			//get value from map
			String value1 = object1.getValue();
			String value2 = object2.getValue();
			return value1.compareTo(value2);
		}		
    });
   
    //creating new map of type LinkedHashMap to maintain insertion order
    Map mapObject = new LinkedHashMap<>();
    Iterator it = listObject.iterator(); 
    while (it.hasNext()) {
           Map.Entry entry = (Map.Entry) it.next();           
           //adding elements one by one to newly 
           mapObject.put(entry.getKey(), entry.getValue());
    }
        
    System.out.println("After sorting by value--------");
	for (Object key : mapObject.keySet()) {
		System.out.println("Key is : " + key.toString() + "   Value is : " + mapObject.get(key));
	}    		   
}
}

Output is –

before sorting by value——–
Key is : 1 Value is : aman
Key is : 2 Value is : ram
Key is : 3 Value is : sohan
Key is : 5 Value is : mohan
Key is : 22 Value is : rahul
Key is : 9 Value is : rohit
After sorting by value——–
Key is : 1 Value is : aman
Key is : 5 Value is : mohan
Key is : 22 Value is : rahul
Key is : 2 Value is : ram
Key is : 9 Value is : rohit
Key is : 3 Value is : sohan

Adding user-defined class as key in HashMap.

In this example, We will add the user-defined class as the key to HashMap and will retrieve the value using this key.

 

package addingcustomobjectinhashmap;
import java.util.*;
class Book {
	
	private String bookName;

	public String getBookName() {
		return bookName;
	}

	public void setBookName(String bookName) {
		this.bookName = bookName;
	}

	public Book(String bookName) {
		super();
		this.bookName = bookName;
	}		
}
public class Example {
public static void main(String[] args) {
		
	Map<Book,String> hashMapObj = new HashMap();
	Book b1 = new Book("abc");
	Book b2 = new Book("pqr");
	Book b3 = new Book("xyz");

	hashMapObj.put(b1, "value1");
	hashMapObj.put(b2, "value2");
	hashMapObj.put(b3, "value3");				
	Set<Map.Entry<Book, String>> set = hashMapObj.entrySet();	
	for(Map.Entry<Book, String> entry : set) {	
		System.out.println("retrieving value using book object as key is "+hashMapObj.get(entry.getKey()));	
	}	
}
}

Output is –

retrieving value using book object as key is value1
retrieving value using book object as key is value2
retrieving value using book object as key is value3

 

What will happen if we will have the same for the name variable?

package addingcustomobjectinhashmap;
import java.util.*;
class Book {
	
	private String bookName;

	public String getBookName() {
		return bookName;
	}

	public void setBookName(String bookName) {
		this.bookName = bookName;
	}

	public Book(String bookName) {
		super();
		this.bookName = bookName;
	}	
}
public class Example {
public static void main(String[] args) {
		
	Map<Book,String> hashMapObj = new HashMap();
	Book b1 = new Book("abc");
	Book b2 = new Book("abc");
	Book b3 = new Book("abc");

	hashMapObj.put(b1, "value1");
	hashMapObj.put(b2, "value2");
	hashMapObj.put(b3, "value3");		
	Set<Map.Entry<Book, String>> set = hashMapObj.entrySet();	
	for(Map.Entry<Book, String> entry : set) {	
		System.out.println("retrieving value using book object as key is "+hashMapObj.get(entry.getKey()));
		
	}
	
}
}

Output is –

retrieving value using book object as key is value3
retrieving value using book object as key is value1
retrieving value using book object as key is value2

 

Still, we have the same output.

Let’s override equals() and hashcode() method.

package addingcustomobjectinhashmap;
import java.util.*;
class Book {
	
	private String bookName;

	public String getBookName() {
		return bookName;
	}

	public void setBookName(String bookName) {
		this.bookName = bookName;
	}

	public Book(String bookName) {
		super();
		this.bookName = bookName;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((bookName == null) ? 0 : bookName.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Book other = (Book) obj;
		if (bookName == null) {
			if (other.bookName != null)
				return false;
		} else if (!bookName.equals(other.bookName))
			return false;
		return true;
	}

	
	
	
	
}
public class Example {
public static void main(String[] args) {
	
	
	Map<Book,String> hashMapObj = new HashMap();
	Book b1 = new Book("abc");
	Book b2 = new Book("abc");
	Book b3 = new Book("abc");

	hashMapObj.put(b1, "value1");
	hashMapObj.put(b2, "value2");
	hashMapObj.put(b3, "value3");
	
	
	
	
	Set<Map.Entry<Book, String>> set = hashMapObj.entrySet();
	
	for(Map.Entry<Book, String> entry : set) {
	
		System.out.println("retrieving value using book object as key is "+hashMapObj.get(entry.getKey()));

		
	}
	
}
}

 

Output is – retrieving value using book object as key is value3

Performance in the case of HashMap and Hashtable.

We will see a simple example where we will see the time taken by HashMap and time taken by Hashtable for the same elements.

 

package hashmap;

import java.util.*;

//import org.joda.time.LocalDate;

public class Test2 {

public static void main(String[] args) {
	
	    // define ArrayList Object
	    Map<Integer, String> hashmapObject = new HashMap<>();		
		//get current time in milliseconds
		long l1 = System.currentTimeMillis();
		for(int i=0; i<1000000; i++) {
			//add ram 1M times
			hashmapObject.put(2, "ram");
		}
		//get current time in milliseconds
		long l2 = System.currentTimeMillis();
				
		//l2 - l1 will return time took to add 1M times ram in listOfArrayList
		System.out.println("time taken by HashMap "+(l2-l1));
		
		long l3 = System.currentTimeMillis();
		Map<Integer, String> hashtableObject = new Hashtable<>();
		for(int i=0; i<1000000; i++) {
			hashtableObject.put(2,"ram");
		}
				
		long l4 = System.currentTimeMillis();		
		//l2 - l1 will return time took to add 1M times ram in listOfVector
		System.out.println("time taken by Hashtable "+(l4-l3));							
}
}

Output is –

time taken by HashMap 21
time taken by Hashtable 54

 

Example to define Read-Only HashMap.

Collection class provides unmodifiableMap(Map<? extends K,? extends V> m) method, using that we can create unmodifiable HashMap.

Note – For List and Set we have Collections.unmodifiableList() and Collections.unModifiableSet() methods. Let’s see an exmaple.

 

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

public class ReadOnlyMapExp {
	public static void main(String[] args) {

		Map<Integer, String> mapObject = new HashMap<>();

		mapObject.put(2, "ram");
		mapObject.put(4, "mohan");
		mapObject.put(9, "sohan");
		mapObject.put(7, "rohan");

		for (Map.Entry<Integer, String> entry : mapObject.entrySet()) {
			System.out.println("Key = " + entry.getKey() + ", Value = "
					+ entry.getValue());

		}

		// let's create a new map using unmodifiableMap()
		Map<Integer, String> readOnlyMap = Collections
				.unmodifiableMap(mapObject);

		// add new element
		readOnlyMap.put(10, "chiku"); // as soon as we will add new element
										// exception will come
		System.out.println(readOnlyMap);

	}

}

Output is –

Key = 2, Value = ram
Key = 4, Value = mohan
Key = 7, Value = rohan
Key = 9, Value = sohan
Exception in thread “main” java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableMap.put(Unknown Source)
at ReadOnlyMapExp.main(ReadOnlyMapExp.java:26)

Once our HashMap is immutable we can’t add elements to it.

 

Different ways to iterate HashMap in Java.

Using Iterator – Iterating HashMap using an iterator.

We will use HashMap’s entrySet() method which returns a Set type of Map.Entry, something like (Set<Map.Entry<K,V>>).

package treemapexp;
 
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
 
class HashMapExample {
	public static void main(String[] arg) {
		Map<Integer, String> hashmapObject = new HashMap<>();
 
		hashmapObject.put(2, "ram");
		hashmapObject.put(3, "mohan");
		hashmapObject.put(4, "Bangalore");
		hashmapObject.put(5, "Rakesh");
 
		// we will iterate using Iterator
		Iterator<Map.Entry<Integer, String>> iterator = hashmapObject
				.entrySet().iterator();
 
		while (iterator.hasNext()) {
			Map.Entry<Integer, String> entry = iterator.next();
			System.out.println("Key is = " + entry.getKey() + ", Value is = "
					+ entry.getValue());
		}
	}
}

Output is –

Key is = 2, Value is = ram
Key is = 3, Value is = mohan
Key is = 4, Value is = Bangalore
Key is = 5, Value is = Rakesh

 

Using for each loop -Iterating HashMap using for each loop.

First use entrySet() method then for each loop.

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

public class HashMapExample1 {
	public static void main(String[] args) {
		Map<Integer, String> hashMapObj = new HashMap<>();

		hashMapObj.put(2, "ram");
		hashMapObj.put(5, "mohan");
		hashMapObj.put(3, "sohan");

		Set<Map.Entry<Integer, String>> entrySet = hashMapObj.entrySet();

		for (Map.Entry<Integer, String> entry : entrySet) {
			System.out.println("Key is : " + entry.getKey() + "   Value is : "
					+ entry.getValue());
		}
	}
}

Output is –

Key is : 2 Value is : ram
Key is : 3 Value is : sohan
Key is : 5 Value is : mohan

 

Using Lambda expression – Iterating HashMap using lambda expression.

We can also iterate HashMap using lambda expression as below.

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

public class HashMapExample1 {
	public static void main(String[] args) {
		Map<Integer, String> hashMapObj = new HashMap<>();

		hashMapObj.put(2, "ram");
		hashMapObj.put(5, "mohan");
		hashMapObj.put(3, "sohan");
		hashMapObj.put(9, "rohit");

		hashMapObj.forEach((k, v) -> {
			System.out.println("Key is : " + k + "   Value is : " + v);
		});

	}
}

Output is –

Key is : 2 Value is : ram
Key is : 3 Value is : sohan
Key is : 5 Value is : mohan
Key is : 9 Value is : rohit

Using java 8 stream() method –

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

public class HashMapExample1 {
	public static void main(String[] args) {
		Map<Integer, String> hashMapObj = new HashMap<>();

		hashMapObj.put(2, "ram");
		hashMapObj.put(5, "mohan");
		hashMapObj.put(3, "sohan");
		hashMapObj.put(9, "rohit");

		Set<Map.Entry<Integer, String>> setReference= hashMapObj.entrySet();

		setReference.stream().forEach
		(mapEntry-> System.out.println("Key is : "+mapEntry.getKey()+"   Value is : "+mapEntry.getValue()));
	}
}

Output is –

Key is : 2 Value is : ram
Key is : 3 Value is : sohan
Key is : 5 Value is : mohan
Key is : 9 Value is : rohit

 

Using the keySet() and Iterator – 

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

public class HashMapExample1 {
	public static void main(String[] args) {
		Map<Integer, String> hashMapObj = new HashMap<>();

		hashMapObj.put(2, "ram");
		hashMapObj.put(5, "mohan");
		hashMapObj.put(3, "sohan");
		hashMapObj.put(9, "rohit");

		Iterator iterator = hashMapObj.keySet().iterator();

		while (iterator.hasNext()) {
			Integer key = (Integer) iterator.next();

			System.out.println("Key is : " + key + "   Value is : " + hashMapObj.get(key));
		}
	}
}

Output is –

Key is : 2 Value is : ram
Key is : 3 Value is : sohan
Key is : 5 Value is : mohan
Key is : 9 Value is : rohit

 

Using keySet() and for each loop – 

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

public class HashMapExample1 {
	public static void main(String[] args) {
		Map<Integer, String> hashMapObj = new HashMap<>();

		hashMapObj.put(2, "ram");
		hashMapObj.put(5, "mohan");
		hashMapObj.put(3, "sohan");
		hashMapObj.put(9, "rohit");

		for (Integer key : hashMapObj.keySet()) {
			System.out.println("Key is : " + key + "   Value is : " + hashMapObj.get(key));
		}
	}
}

output is –

Key is : 2 Value is : ram
Key is : 3 Value is : sohan
Key is : 5 Value is : mohan
Key is : 9 Value is : rohit

 

Constructors of HashMap in Java.

Here we will see Constructors and methods of HashMap in Java. There are four constructors defined for HashMap.

  • HashMap()
  • HashMap(int initialCapacity)
  • HashMap(int initialCapacity, float loadFactor)
  • HashMap(Map map)

HashMap() – This is a default constructor that is used to create new and empty HashMap with initial capacity 16 and the load factor .75. Inside this constructor, we initialize the load factor with its default value i.e 0.75f  Let’s see the internal code of this constructor.

  public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

 

Let’s see an example.

package hashmap;
import java.util.*;
public class HashMapConstructor1 {
public static void main(String[] args) {
	
	//creating HashMap object using default constructor
	Map<Integer, String> hashmapObject = new HashMap<>();
	 
	hashmapObject.put(2, "ram");
	hashmapObject.put(8, "mohan");
	hashmapObject.put(4, "Bangalore");
	hashmapObject.put(5, "Rakesh");

	// we will iterate using Iterator
	Iterator<Map.Entry<Integer, String>> iterator = hashmapObject
			.entrySet().iterator();

	while (iterator.hasNext()) {
		Map.Entry<Integer, String> entry = iterator.next();
		System.out.println("Key is = " + entry.getKey() + ", Value is = "
				+ entry.getValue());
	}
}
}

Output is –

Key is = 2, Value is = ram
Key is = 4, Value is = Bangalore
Key is = 5, Value is = Rakesh
Key is = 8, Value is = mohan

HashMap(int initialCapacity) –  We can create a new HashMap defining some different capacity than 16 using this constructor(default factor still will be 0.75f).

Internal implementation –

  
static final float DEFAULT_LOAD_FACTOR = 0.75f;
public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

Example –

package hashmap;

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

public class HashMapConstructor2 {
public static void main(String[] args) {
	
	//creating HashMap object using initial capacity 20
	Map<Integer, String> hashmapObject = new HashMap<>(20);
	 
	hashmapObject.put(2, "ram");
	hashmapObject.put(8, "mohan");
	hashmapObject.put(4, "Bangalore");
	hashmapObject.put(5, "Rakesh");

	// we will iterate using Iterator
	Iterator<Map.Entry<Integer, String>> iterator = hashmapObject
			.entrySet().iterator();

	while (iterator.hasNext()) {
		Map.Entry<Integer, String> entry = iterator.next();
		System.out.println("Key is = " + entry.getKey() + ", Value is = "
				+ entry.getValue());
	}
}
}

Output is –

Key is = 2, Value is = ram
Key is = 4, Value is = Bangalore
Key is = 5, Value is = Rakesh
Key is = 8, Value is = mohan

HashMap(int initialCapacity, float loadFactor) – We can also create a new HashMap with new capacity as well as new load factor, rather than 16 and 0.75.

Internal implementation –

 public HashMap(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);
        this.loadFactor = loadFactor;
        this.threshold = tableSizeFor(initialCapacity);
    }

 

Example –

package hashmap;

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

public class HashMapConstructor3 {
public static void main(String[] args) {
	
	//creating HashMap object using initial capacity 20 and load factor 0.80f
	Map<Integer, String> hashmapObject = new HashMap<>(20,0.80f);
	 
	hashmapObject.put(2, "ram");
	hashmapObject.put(8, "mohan");
	hashmapObject.put(4, "Bangalore");
	hashmapObject.put(5, "Rakesh");
	

	// we will iterate using Iterator
	Iterator<Map.Entry<Integer, String>> iterator = hashmapObject
			.entrySet().iterator();

	while (iterator.hasNext()) {
		Map.Entry<Integer, String> entry = iterator.next();
		System.out.println("Key is = " + entry.getKey() + ", Value is = "
				+ entry.getValue());
	}
}
}

Output is –

Key is = 2, Value is = ram
Key is = 4, Value is = Bangalore
Key is = 5, Value is = Rakesh
Key is = 8, Value is = mohan

HashMap(Map map) – We can pass any type of classes which implements Map interface and can convert it into HashMap. For example, we are going to convert Hashtable into HashMap in the below example before that let’s see how this constructor has been defined in the HashMap class.

Internal implementation –

 public HashMap(Map<? extends K, ? extends V> m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        putMapEntries(m, false);
    }

Example –

package hashmap;

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

public class HashMapConstructor4 {
public static void main(String[] args) {
	//creating Hashtable object using, later we will convert into HashMap
		Map<Integer, String> hashtablepObject = new Hashtable<>(20,0.80f);
		 
		hashtablepObject.put(2, "ram");
		hashtablepObject.put(8, "mohan");
		hashtablepObject.put(4, "Bangalore");
		hashtablepObject.put(5, "Rakesh");

		// we will convert Hashtable into HashMap using below constructor
		HashMap<Integer,String> hashMapObj = new HashMap<>(hashtablepObject);
		Iterator<Map.Entry<Integer, String>> iterator = hashMapObj
				.entrySet().iterator();

		while (iterator.hasNext()) {
			Map.Entry<Integer, String> entry = iterator.next();
			System.out.println("Key is = " + entry.getKey() + ", Value is = "
					+ entry.getValue());
		}
}
}

Output is –

Key is = 8, Value is = mohan
Key is = 2, Value is = ram
Key is = 4, Value is = Bangalore
Key is = 5, Value is = Rakesh

That’s all about HashMap in Java With Example.

You may like.

HashMap docs.