Content about Java ERP Solution for Reviews Best ERP Software for sale and Free Software with Java OpenSource for Free Download

Java Hashmap Example example code to using Hashmap in Java

HashMap is a Collection Class in package java.util
HashMap store data with key and value for example in below

Example to using HashMap in Java

 package example.util;  
 import java.util.*;  
 public class HashmapExample {  
   public void hashmapExample(){  
     //Create HashMap Object  
     HashMap<String,String> hashmap=new HashMap<String,String>();  
     //Store and Remove data from HashMap  
     hashmap.put("key1", "value1");  
     hashmap.put("key2", "value2");  
     hashmap.put("key3", "value3");  
     String key3=hashmap.remove("key3");  
     //Get Value from HashMap by using Key  
     System.out.println("-- Example for Get Value from HashMap --");  
     System.out.println("Get Hashmap value: "+hashmap.get("key1"));  
     System.out.println("Remove Hashmap value: "+key3);  
     System.out.println("Contains Key Hashmap: "+hashmap.containsKey("key1"));  
     System.out.println("Contains Key Hashmap: "+hashmap.containsKey("key3"));  
     System.out.println("Contains Value Hashmap: "+hashmap.containsValue("value1"));  
     System.out.println("Contains Value Hashmap: "+hashmap.containsValue("value3"));  
     //Loop data from HashMap by keySet and using key to get the Value  
     System.out.println("-- Example for Iterate list from Hash Map --");  
     Iterator<String> it=hashmap.keySet().iterator();  
     while(it.hasNext()){  
       String key=it.next();  
       String value=hashmap.get(key);  
       System.out.println("By Key :Key : "+key+"  Value: "+value);  
     }  
     //Loop data from HashMap by Value List all value no need to using Key  
     it=hashmap.values().iterator();  
     while(it.hasNext()){  
       System.out.println("Value "+it.next());  
     }             
   }  
   public static void main (String args[]){  
     //Test run program in main method  
     HashmapExample hashmap=new HashmapExample();  
     hashmap.hashmapExample();  
   }  
 }  
Output when Run Test Program

-- Example for Get Value from HashMap --
Get Hashmap value: value1
Remove Hashmap value: value3
Contains Key Hashmap: true
Contains Key Hashmap: false
Contains Value Hashmap: true
Contains Value Hashmap: false
-- Example for Iterate list from Hash Map --
By Key :Key : key2   Value: value2
By Key :Key : key1   Value: value1
Value value2
Value value1