Collection-4 || HashMap in Collection.

HashMap is a class that implements the Map interface. A map stores data in the Key-Value pair. HashMap uses the same technique to store values.

Learn Hashmap in Collection.
  • Class: HashMap
  • Interface: Map
  • Package: java.util

We can never lose any data as we are tagging each element with a key. While using an index we can lose data because the index may change due to the insertion or deletion of the element.

  • Removes the indexing concept.
  • Stores data in Key/Value pair
  • Retrieval of data using key is very fast.
  • Key can be of any type String as well as Integer It can be String/Integer, Integer/String, String/String or Integer/Integer.
  • Mixed type of HashMap is also allowed
  • Adding values to the HashMap using put(key, value)
  • The order of elements is not consistent. While printing it sorts the list in ascending order and removes all duplicate keys, For duplicate key, it returns the last occurrence. (Actually while sorting, it replaces the value of key each time and at the end, last value remains stored in the key).
  • We can access individual items using the key only. Not index or item value.
  • get(key) – return null if key not found in the list.
  • The null keyword can be used for both key and value.
  • Duplicate keys are allowed(including null) but it is against the rule. It returns the last entry in the list which can be retrieved based on Key using get(key).
  • Checks and returns the status of the presence of key or value in the HashMap using containsKey(key) and containsValue(value) methods.
  • Traversing HashMap using the For-each loop via keys only. It returns unique keys via keySet() method.
  • Traversing HashMap using a for-each loop via values only. It returns unique values via values() method.
  • Traversing Printing both keys and values using the for-each loop based on unique keys only.
  • Remove items based on key using remove(key) method.
  • Remove items based on key and value combination when we want to remove entry based on the value, using remove(key, value) method.
  • Getting the size of HashMap using size(), it returns the count of unique keys only.
  • Remove all the items from the list using clear()
  • We can’t change/update the key in the hashmap. We can only remove the old key then add a new key item.
  • Replacing values for a specific key using replace(key, value) and replace(key, old_value,new_value)
  • Traversing HashMap using entrySet() and for-each loop.
  • Traversing HashMap using the Iterator via entrySet().iterator()
  • Traversing and perform an action on each element in the HashMap using forEach(action) method.
  • Sorting List using TreeMap.

HashMap Declaration

HashMap<Integer, String> hashMap1=new HashMap<Integer, String>();
HashMap<String, String> hashMap2=new HashMap<String, String>();
Map<String,Integer> hashMapE=new HashMap<String, Integer>();
HashMap map=new HashMap<>();

Adding values to the HashMap using put(key, value)

HashMap<Integer, String> hashMap1=new HashMap<Integer, String>();
		
		// Adding values to the HashMap List
		hashMap1.put(1, "Java");
		hashMap1.put(3, "Selenium");
		hashMap1.put(5, "Appium");

Retrieve value based on the key using get(key)

HashMap<Integer, String> hashMap1=new HashMap<Integer, String>();
		
		// Adding values to the HashMap List
		hashMap1.put(1, "Java");
		hashMap1.put(3, "Selenium");
		hashMap1.put(5, "Appium");
                System.out.println(hashMap1.get(3));
-------------------------------------------------------------
Selenium

While printing it sorts the list in ascending order

HashMap<Integer, String> hashMap1=new HashMap<Integer, String>();
		// Adding values to the HashMap List
		hashMap1.put(1, "Java");
		hashMap1.put(3, "Selenium");
		hashMap1.put(5, "Appium");
		hashMap1.put(2, "C#");
                System.out.println(hashMap1);

HashMap<String, String> hashMap3=new HashMap<String, String>();
		//Adding values to the hashmap list
		hashMap3.put("C", "Java");
		hashMap3.put("D", "C#");
		hashMap3.put("Z", "Selenium");
		hashMap3.put("F", "C");
		hashMap3.put("A", "C");
		System.out.println(hashMap3);

Output:
{1=Java, 2=C#, 3=Selenium, 5=Appium}
{A=C, C=Java, D=C#, F=C, Z=Selenium}

Traversing HashMap using the For-each loop via Keys

Traversing HashMap using the For-each loop via keys only. It returns unique keys via keySet() method.

HashMap<String, String> hashMap4=new HashMap<String, String>();
		//Adding values to the hashmap list
		hashMap4.put("C", "Java");
		hashMap4.put("F", "C1");
		hashMap4.put("D", "C#");
		hashMap4.put("Z", "Selenium");
		hashMap4.put("F", "C");
		hashMap4.put("A", "C");
		hashMap4.put("F", "C2");
		
		System.out.println("\nTraversing HashMap using For-each loop via keys only");
		// Returns unique keys from the hashmap
		for (String string : hashMap4.keySet()) 
		{
			System.out.println(string);	
		}

Outpput:
Traversing HashMap using For-each loop via keys only
A
C
D
F
Z

Traversing HashMap using a for-each loop via values

Traversing HashMap using a for-each loop via values only. It returns unique values via values() method.

HashMap<String, String> hashMap4=new HashMap<String, String>();
		//Adding values to the hashmap list
		hashMap4.put("C", "Java");
		hashMap4.put("F", "C1");
		hashMap4.put("D", "C#");
		hashMap4.put("Z", "Selenium");
		hashMap4.put("F", "C");
		hashMap4.put("A", "C");
		hashMap4.put("F", "C2");
		
		System.out.println("\nTraversing HashMap using for-each loop via values only:");
		// Returns unique values from the hashmap
		for (String string : hashMap4.values()) 
		{
			System.out.println(string);	
		}

Output:
Traversing HashMap using for-each loop via values only:
C
Java
C#
C2
Selenium

Printing both keys and values using the for-each loop

Printing both keys and values using the for-each loop based on unique keys only.

HashMap<String, String> hashMap4=new HashMap<String, String>();
		//Adding values to the hashmap list
		hashMap4.put("C", "Java");
		hashMap4.put("F", "C1");
		hashMap4.put("D", "C#");
		hashMap4.put("Z", "Selenium");
		hashMap4.put("F", "C");
		hashMap4.put("A", "C");
		hashMap4.put("F", "C2");

System.out.println("\nPrint both Key and Values, based on unique keys");
		for (String currentKey : hashMap4.keySet()) 
		{
			System.out.println("Key: "+currentKey+" Value: "+hashMap4.get(currentKey));
			

Output:
Print both Key and Values
Key: A Value: C
Key: C Value: Java
Key: D Value: C#
Key: F Value: C2
Key: Z Value: Selenium

Using containsKey(key) and containsValue(value)

Checks and returns the status of the presence of key or value in the HashMap using containsKey(key) and containsValue(value) methods.

// Creating HashMap having "String Key" and "Integer values"
		HashMap<String, Integer> hashMap5=new HashMap<String, Integer>();
		hashMap5.put("TV",5000);
		hashMap5.put("Refrigerator",8000);
		hashMap5.put("AC", 30000);
		hashMap5.put("Microwave",2000);
		hashMap5.put("Refrigerator",6000);
		hashMap5.put("Laptop",25000);
		hashMap5.put("Laptop", 30000);
		
// Checks if the key is present in the HashMap or not using containsKey(key)
		System.out.println("Key status in the HashMap: "+hashMap5.containsKey("Refrigerator"));
		
// Checks if the value is present in the HashMap or not using the containsValue(values)
		System.out.println("Value status in the Hashmap: "+ hashMap5.containsValue(2000));

Output:
Key status in the HashMap: true
Value status in the Hashmap: true

Duplicate and null keys in HashMap

  1. The null keyword can be used for both key and value.
  2. It removes the duplicate key and keeps the last entry in the list.
          // Declaration of HashMap Objects.
		Map<String,Integer> hashMapE=new HashMap<String, Integer>();
		
	  // Adding values to the HashMap List
		hashMap1.put(1, "Java");
		hashMap1.put(3, "Selenium");
		hashMap1.put(null, "Exception1");
		hashMap1.put(5, "Appium");
		hashMap1.put(2, "C#");
		hashMap1.put(6, null);
		hashMap1.put(null, "Exception");
		hashMap1.put(3, "Exception2");
		
		System.out.println(hashMap1);
----------------------------------------------------------------------
Output:
{null=Exception, 1=Java, 2=C#, 3=Exception2, 5=Appium, 6=null}

Remove items based on key using remove(key)

HashMap<String, String> hashMap3=new HashMap<String, String>();
		//Adding values to the hashmap list
		hashMap3.put("C", "Java");
		hashMap3.put("F", "C1");
		hashMap3.put("D", "C#");
		hashMap3.put("Z", "Selenium");
		hashMap3.put("F", "C");
		hashMap3.put("A", "C");
		hashMap3.put("F", "C2");
				
		System.out.println("hashMap3: "+hashMap3);
		//Remove specific key, it will remove the matching keys from list
		hashMap3.remove("F");
				
		System.out.println("hashMap3: "+hashMap3);
-------------------------------------------------------------------------
Output:
hashMap3: {A=C, C=Java, D=C#, F=C2, Z=Selenium}
hashMap3: {A=C, C=Java, D=C#, Z=Selenium}

Remove items based on key and value combination

Remove items based on key and value combination when we want to remove entry based on the value, using remove(key, value) method.

HashMap<String, String> hashMap3=new HashMap<String, String>();
		//Adding values to the hashmap list
		hashMap3.put("C", "Java");
		hashMap3.put("F", "C1");
		hashMap3.put("D", "C#");
		hashMap3.put("Z", "Selenium");
		hashMap3.put("F", "C");
		hashMap3.put("A", "C");
		hashMap3.put("F", "C2");
				
		System.out.println("hashMap3: "+hashMap3);
		// Remove specific key & value combination from the list
				hashMap3.remove("F", "C2");
				hashMap3.remove("A", "C2");
				
		System.out.println("hashMap3: "+hashMap3);
----------------------------------------------------------------------------
Output:
hashMap3: {A=C, C=Java, D=C#, F=C2, Z=Selenium}
hashMap3: {A=C, C=Java, D=C#, Z=Selenium}

Getting the size of HashMap using size()

  • Getting the size of HashMap using size(), it returns the count of unique keys only.
  • Remove all the items from the list using clear()
HashMap<String, String> hashMap3=new HashMap<String, String>();
		//Adding values to the hashmap list
		hashMap3.put("C", "Java");
		hashMap3.put("F", "C1");
		hashMap3.put("D", "C#");
		hashMap3.put("Z", "Selenium");
		hashMap3.put("F", "C");
		hashMap3.put("A", "C");
		hashMap3.put("F", "C2");
				
		System.out.println("hashMap3 Size: "+hashMap3.size());
		// Remove all the items from the list using clear()
		hashMap3.clear();
		System.out.println("hashMap3 Size: "+hashMap3.size());
-----------------------------------------------------------------------------
Output:
hashMap3 Size: 5
hashMap3 Size: 0

Replacing values using replace()

There are two versions are available for replace() method. Both the methods can replace values for a specific key using replace(key, value) and replace(key, old_value,new_value)

replace(key, value)

replace(key, value): It directly replaces the new value for a specific key and returns the old value.

// Declaration of HashMap Objects.
		HashMap<Integer, String> hashMap1=new HashMap<Integer, String>();

		// Adding values to the HashMap List
		hashMap1.put(1, "Java");
		hashMap1.put(3, "Selenium");
		hashMap1.put(null, "Exception1");
		hashMap1.put(5, "Appium");
		hashMap1.put(2, "C#");
		hashMap1.put(6, null);
		hashMap1.put(null, "Exception");
		hashMap1.put(3, "Exception2");
		
		System.out.println(hashMap1);
		String oldValue=hashMap1.replace(2, "C#1");
		System.out.println("OldValue for key '2': "+oldValue);
		System.out.println(hashMap1);
--------------------------------------------------------------------
Output:
{null=Exception, 1=Java, 2=C#, 3=Exception2, 5=Appium, 6=null}
OldValue for key '2': C#
{null=Exception, 1=Java, 2=C#1, 3=Exception2, 5=Appium, 6=null}

replace(key, old_value, new_value)

replace(key, old_value, new_value): It replaces the value of a key only if the combination of key and old_value passed by the arguments matches in the list.

// Declaration of HashMap Objects.
		Map<String,Integer> hashMapE=new HashMap<String, Integer>();
		HashMap<Integer, String> hashMap1=new HashMap<Integer, String>();
		
		// Adding values to the HashMap List
		hashMap1.put(1, "Java");
		hashMap1.put(3, "Selenium");
		hashMap1.put(null, "Exception1");
		hashMap1.put(5, "Appium");
		hashMap1.put(2, "C#");
		hashMap1.put(6, null);
		hashMap1.put(null, "Exception");
		hashMap1.put(3, "Exception2");
		
		System.out.println(hashMap1);
		boolean result=hashMap1.replace(2, "C#2","C#1");
		System.out.println("Value replaced: "+result);
		System.out.println(hashMap1);
-----------------------------------------------------------------------
Output:
{null=Exception, 1=Java, 2=C#, 3=Exception2, 5=Appium, 6=null}
Value replaced: false
{null=Exception, 1=Java, 2=C#, 3=Exception2, 5=Appium, 6=null}

Traversing via entrySet() and for-each loop

HashMap<String, Integer> hashMap5=new HashMap<String, Integer>();
		hashMap5.put("TV",5000);
		hashMap5.put("Refrigerator",8000);
		hashMap5.put("AC", 30000);
		hashMap5.put("Microwave",2000);
		hashMap5.put("Refrigerator",6000);
		hashMap5.put("Laptop",25000);
		hashMap5.put("Laptop", 30000);
		
		for(Map.Entry<String, Integer> currentEntry: hashMap5.entrySet())
		{
			System.out.println(currentEntry.getKey()+"->"+currentEntry.getValue());
		}
---------------------------------------------------------------------
Output:
Laptop->30000
TV->5000
AC->30000
Microwave->2000
Refrigerator->6000

Traversing HashMap using the Iterator

HashMap<String, Integer> hashMap5 = new HashMap<String, Integer>();
		hashMap5.put("TV", 5000);
		hashMap5.put("Refrigerator", 8000);
		hashMap5.put("AC", 30000);
		hashMap5.put("Microwave", 2000);
		hashMap5.put("Refrigerator", 6000);
		hashMap5.put("Laptop", 25000);
		hashMap5.put("Laptop", 30000);
// Traverse using Iterator
		Iterator iterator = hashMap5.entrySet().iterator();
		System.out.println("Method to use Iterator");
		while (iterator.hasNext())
		{
			System.out.println(iterator.next());
		}
---------------------------------------------------------------------
Output:
Method to use Iterator
Laptop=30000
TV=5000
AC=30000
Microwave=2000
Refrigerator=6000

Traversing forEach(action) method.

HashMap<String, Integer> hashMap5 = new HashMap<String, Integer>();
		hashMap5.put("TV", 5000);
		hashMap5.put("Refrigerator", 8000);
		hashMap5.put("AC", 30000);
		hashMap5.put("Microwave", 2000);
		hashMap5.put("Refrigerator", 6000);
		hashMap5.put("Laptop", 25000);
		hashMap5.put("Laptop", 30000);
		
		System.out.println("Traversing using forEach(action) method:");
				hashMap5.forEach((key, value) -> System.out.println(key + " " + value));
-------------------------------------------------------------------------------
Output:
Traversing using forEach(action) method:
Laptop 30000
TV 5000
AC 30000
Microwave 2000
Refrigerator 6000

Sorting List using TreeMap

  • A TreeMap list always remains in a natural sorted order based on the Keys as mentioned below:
    • Integer: in ascending order
    • String: in alphabetically ascending order

The below program is an example of a sorted and unsorted list.

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class HashMapWithTree {

	public static void main(String[] args) {
		
		HashMap<Integer,String> unsortedMap=new HashMap<Integer, String>();
		TreeMap<Integer,String> sortedMap=new TreeMap<Integer, String>();
		
		System.out.println("Sorted List:");
		traverseList(sortedMap);
		
		System.out.println("\nUnsorted List:");
		traverseList(unsortedMap);
	}
	
	public static void traverseList(Map<Integer,String> map)
	{
		map.put(5, "Five");
		map.put(1,"One");
		map.put(10, "Ten");
		map.put(3,"Three");
		map.put(15,"Fifteen");
		map.put(20,"Twenty");
		map.put(11,"Eleven");
		map.put(2,"Two");
		map.put(4,"Four");
		map.put(9,"Nine");
		map.put(6,"Six");
		map.put(8,"Eight");
		
		for(Integer key:map.keySet())
		{
			System.out.println(key+": "+map.get(key));
		}
	}
}
Output:
Sorted List:
1: One
2: Two
3: Three
4: Four
5: Five
6: Six
8: Eight
9: Nine
10: Ten
11: Eleven
15: Fifteen
20: Twenty

Unsorted List:
1: One
2: Two
3: Three
20: Twenty
4: Four
5: Five
6: Six
8: Eight
9: Nine
10: Ten
11: Eleven
15: Fifteen

1144total visits,4visits today

Leave a Reply

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