HashMap in Java

HashMap provides the basic implementation of Map interface of Java. HashMap stores the data in (Key, Value) pairs. 

  • To access a value one must know its key.
  • HashMap doesn’t allow duplicate keys but allows duplicate values.
  • HashMap allows null key also but only once and multiple null values.
  • it is a part of Java’s collection since Java 1.2.
  • HashMap is a part of java.util package.
  • HashMap extends an abstract class AbstractMap which also provides an incomplete implementation of Map interface.

Code Example:

Package basichashmaps;

import java.util.HashMap;

public class BasicHashMaps
	static HashMap<String, Boolean> map = new HashMap<>();
	public static void main(String[] args)
	  //Add Key-Value pair using PUT
	  map.put("Kenny", true);
	  map.put("Joe", false);
	  //Retrieve Value by key using GET
	  //Remove Key-Value pair using remove

	  if(map.containsKey("Jack")) System.out.println("Key Jack Present");
	  if(map.containsValue(Boolean.FALSE)) System.out.println("Value FALSE Present");
	  for (String s : map.keySet())
		System.out.println("Loop through Key set");
	  for (Boolean b : map.Values())
		System.out.println("Loop through value set");
	  for (Map.Entry kv : map.entrySet())
		System.out.println("Loop through Key Value");

Leave a Reply