javacodex.com
Java Examples
Java Examples
memu home questions

Basic HashMap Example

HashMap is an object that stores a key and value as a pairs.

Source: (MyHashMap.java)

import java.util.*;
 
public class MyHashMap {
 
   public static void main(String args[]){
 
      HashMap<String, String> map = new HashMap<String, String>();
      map.put("Tom1", "Tom Jones");
      map.put("Tom2", "Tom Sawyer");
      map.put("Tom3", "Tom Hanks");
      System.out.println("Size of Map "+ map.size());
      System.out.println("Remove Tom Hanks");
      map.remove("Tom3");
      System.out.println("Size of Map "+ map.size());
 
      Iterator<String> it = map.keySet().iterator();
      while(it.hasNext()){
         String key = it.next();
         System.out.println(key + " : " + map.get(key));
      }
   }
}
 

Output:

$ java MyHashMap 
Size of Map 3
Remove Tom Hanks
Size of Map 2
Tom2 : Tom Sawyer
Tom1 : Tom Jones

Contact: javacodex@yahoo.com