Java HashMap - The Coding Shala

Home >> Learn Java >> Java HashMap

Java HashMap

In this post, we will see what is Java HashMap and its implementation with example.

Java HashMap is a part of Java collections. The HashMap is a data structure that is used to store (key, value) pairs. In HashMap keys are unique contains values. The HashMap does not maintain the order that means it does not return the keys and values in the same order in which they were inserted into the HashMap.

Java HashMap Implementation

The following Java program explains the basic implementation of Java HashMap: 

import java.util.HashMap;

//HashMap Example

class Main{
 public static void main(String[] args) {
  //initialize hashmap
  HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
  
  //insert key value pair
  //we use put(key, value) method
  map.put(1,10);
  map.put(2,20);
  map.put(3,30);
  System.out.println("Map is: "+map);
  
  //we can also use putIfAbsent(key,value) method
  map.putIfAbsent(4,40);
  map.putIfAbsent(3,50);
  System.out.println("Map is: "+map);
  
  //if we use put() method and key
               // is already exists then it will update value of key
  map.put(1,50);
  System.out.println("Map is"+map);
  
  //get the value of key
  //use get(key) method
  System.out.println("Value of key 1 is: "+map.get(1));
  
  //remove key value pair
  //use remove(key) method
  map.remove(1);
  System.out.println("Map is: "+map);
  
  //check if key is present or not
  //use containsKey(key) method
  System.out.println("Key 2 is present in map? "+map.containsKey(2));
  
  //size of map size() method
  System.out.println("Size of map is: "+map.size());
  
  //iterator map
  System.out.println("Map is: ");
  for(HashMap.Entry<Integer, Integer> entry : map.entrySet()) {
   System.out.println(entry.getKey()+"->"+entry.getValue());
  }
  
  //clear hash map
  //use clear() method
  map.clear();
  
  //check empty
  //use isEmpty() method
  System.out.println("Map is empty? "+map.isEmpty());
 }
}
Output: 

Map is: {1=10, 2=20, 3=30}
Map is: {1=10, 2=20, 3=30, 4=40}
Map is{1=50, 2=20, 3=30, 4=40}
Value of key 1 is: 50
Map is: {2=20, 3=30, 4=40}
Key 2 is present in map? true
Size of map is: 3
Map is: 
2->20
3->30
4->40
Map is empty? true


Other Posts You May Like
Please leave a comment below if you like this post or found some error, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Add two numbers in Scala - The Coding Shala

LeetCode - Number of Good Pairs Solution - The Coding Shala

Richest Customer Wealth LeetCode Solution - The Coding Shala