HashMap in Java

HashMap is one of the most used collections in Java. It is used to store key value pair. The size of HashMap increases as more key value pairs are added. Let us look at sample declaration of HashMap:

HashMap<Integer,String> dummy = new HashMap<Integer,String>();

In above sample the key stored will be of type Integer and corresponding value will be of String type. Let us look at important points of HashMap :-

  1. The key entered in HashMap should be unique i.e key cannot be repeated in the HashMap.
  2. Only one null value can be assigned as the key.
  3. HashMap class is present in java.util package.
  4. It implements the Map interface.

Let us look at the code to understand about HashMap :

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

public class Tech4Humans {

	public static void main(String[] args) {
		
		HashMap<Integer,String> map1 = new HashMap<Integer,String>();
		map1.put(10, "hello");
		map1.put(20, "world");
		System.out.println(map1);
		
		HashMap<String,String> map2 = new HashMap<String,String>();
		map2.put("one", "This");
		map2.put("two", "Bye");
		map2.put("three", "Say");
		map2.put("four", "Great");
		System.out.println(map2);
		
		
		System.out.println("\nHashMap printing using keySet():");
		//accessing HashMap using keySet()
		Set<String> keys = map2.keySet();
		for(String keyTemp:keys) {
			System.out.println("Key = "+keyTemp+", Value = "+map2.get(keyTemp));
		}
		

		System.out.println("\nHashMap printing using entrySet():");
		//accessing HashMap using entrySet()
		Set<Entry<String,String>> keyValues = map2.entrySet();
		for(Entry<String,String> temp : keyValues) {
			System.out.println("Key = "+temp.getKey()+", Value = "+temp.getValue());
		}
	}

}

Output

{20=world, 10=hello}
{four=Great, one=This, two=Bye, three=Say}

HashMap printing using keySet():
Key = four, Value = Great
Key = one, Value = This
Key = two, Value = Bye
Key = three, Value = Say

HashMap printing using entrySet():
Key = four, Value = Great
Key = one, Value = This
Key = two, Value = Bye
Key = three, Value = Say

In the above code we have seen how to create a HashMap and access it using 2 methods – keySet() and entrySet()

Let us look at what happens when we enter duplicate keys and values in HashMap.

Leave a Comment