Java - HashMap example

Posted on October 23, 2016


A simple HashMap example is shown below. In this example we will show you various operations performed by the HashMap like

  • Adding key and value to the HashMap.
  • Retrieving value by passing key from the HashMap.
  • Removing key and its value from the HashMap.
  • Getting size of the HashMap.
  • Checking if a key exist in the HashMap or not.
  • Checking if a value exist in HashMap or not.
  • Removing all keys and values from the HashMap.

HashMapExample.java

package com.boraji.tutorial;

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

/**
 * @author imssbora
 *
 */
public class HashMapExample {
	public static void main(String[] args) {
		Map<String, String> map=new HashMap<>();
		/*Adding key and values in HashMap*/
		map.put("1", "One");
		map.put("2", "Two");
		map.put("3","Three");
		map.put("4", "Four");
		map.put("5", "Five");
		
		System.out.println("HashMap key-values:"+map);
		
		/*Get value by key from the HashMap*/
		System.out.println("Value of '4' is: "+map.get("4"));
		
		/*Removing key and value from the HashMap	*/
		map.remove("4");
		System.out.println("After removal HashMap : " +map);
		
		/*Getting size of HashMap*/
		System.out.println(" Size of HashMap is : "+map.size());
		
		/*Checking if key exist in the HashMap or not*/
		System.out.println("Key '3' exist: "+map.containsKey("3"));
		
		/*Checking if value exist in the HashMap or not*/
		System.out.println("Key '6' exist: "+map.containsValue("6"));
		
		/*Remove all keys and values from the HashMap*/
		map.clear();
		System.out.println("After clearing map: "+map);
	}
}

Output

HashMap key-values:{1=One, 2=Two, 3=Three, 4=Four, 5=Five}
Value of '4' is: Four
After removal HashMap : {1=One, 2=Two, 3=Three, 5=Five}
Size of HashMap is : 4
Key '3' exist: true
Key '6' exist: false
After clearing map: {}