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
  System.out.println("Map is: "+map);
  //we can also use putIfAbsent(key,value) method
  System.out.println("Map is: "+map);
  //if we use put() method and key
               // is already exists then it will update value of key
  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
  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()) {
  //clear hash map
  //use clear() method
  //check empty
  //use isEmpty() method
  System.out.println("Map is empty? "+map.isEmpty());

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: 
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.


Popular Posts from this Blog

LeetCode - Crawler Log Folder Solution - The Coding Shala

Richest Customer Wealth LeetCode Solution - The Coding Shala

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

First Unique Character in a String Java - The Coding Shala

Add two numbers in Scala - The Coding Shala