Sunday, 22 March 2015

Java HashMap Example

A HashMap contains values based on the key. It implements the Map interface and extends AbstractMap class.
It contains only unique elements.
It may have one null key and multiple null values.
It maintains no order.
HashMap is not Synchronized means multiple threads can work Simultaneously.

Hierarchy of HashMap class:




Examples of HashMap class:

import java.util.*;  
public class HashMapDemo{  
 public static void main(String args[]){  
   
  HashMap<Integer,String> hm=new HashMap<Integer,String>();  
  
  hm.put(100,"Struts");  
  hm.put(101,"Hibernate");  
  hm.put(102,"Spring");  
  
   for(Entry<Integer, String> m:hm1.entrySet()){  
   System.out.println(m.getKey()+" "+m.getValue());  
  }   
 }  
}  

Output:
               102 Spring
               100 Struts
               101 Hibernate


public class HashMapExp
{
public static void main(String args[])
{
HashMap<Integer,Float> hm=new HashMap<Integer,Float>();
hm.put(10, 10.5f);
hm.put(20,20.5f);
hm.put(30,30.5f);
hm.put(40,40.5f);
hm.put(null,50.5f);
hm.put(null,60.5f);  // only one null allow
  System.out.println(hm);
  System.out.println(hm.values());
  System.out.println(hm.keySet());
  System.out.println(hm.get(20));
}
}


Output:
[null=60.5, 20=20.5, 10=10.5, 40=40.5, 30=30.5]
[60.5, 20.5, 10.5, 40.5, 30.5]
[Null, 20, 10, 30, 40]
[20.5]