Register Now

Login

Lost Password

Enter your email to reset your password.

BY Author

Java – HashMap Class

Declaration

class HashMap<k,V>

The HashMap class extends abstract class AbstractMap & implements the Map interface.

It uses hash table as a data structure to store the map.

HashMap does not maintain insertion order of its elements.

It can contain only one null Key and many null values.

K specifies key.

V specifies value.

List of HashMap Constructors (CLICK HERE)

List of HashMap Methods (CLICK HERE)

Non Generic Demo

Non generic HashMap can contain any type of keys & values.

Example

 import java.util.HashMap;
 import java.util.Iterator;
 import java.util.Map;
 import java.util.Set;

 public class NonGenericHashMapDemo
 {
     public static void main(String args[]) 
     {
         HashMap hm = new HashMap();
         hm.put("James",5000);
         hm.put("Rohit",6000);
         hm.put("Poonam",7000);
         hm.put("Daisy",8000);
         hm.put("Ricky",9000);
	      
         System.out.println(hm);
	      
         System.out.println("\n After using Iterator :: ");
	      
         Set s = hm.entrySet();
         Iterator itr = s.iterator();
	      
         while(itr.hasNext())
         {
             Map.Entry m = (Map.Entry)itr.next();
             System.out.println("Salary of "+m.getKey() + " is "+m.getValue());
         }
     }
 }

Output

{Rohit=6000, James=5000, Daisy=8000, Poonam=7000, Ricky=9000}

After using Iterator ::
Salary of Rohit is 6000
Salary of James is 5000
Salary of Daisy is 8000
Salary of Poonam is 7000
Salary of Ricky is 9000

Generic Demo

Generic type HashMap allows storing keys & values only of type, specified during declaration.

Example

 import java.util.HashMap;
 import java.util.Iterator;
 import java.util.Map;
 import java.util.Map.Entry;
 import java.util.Set;

 public class GenericHashMapDemo 
 {
     public static void main(String args[]) 
     {
         HashMap<String, Integer> hm = new HashMap<String, Integer>();
         hm.put("James",5000);
         hm.put("Rohit",6000);
         hm.put("Poonam",7000);
         hm.put("Daisy", 8000);
         hm.put("Ricky", 9000);
	      
         System.out.println(hm);
	      
         System.out.println("\n After using Iterator :: ");
	      
         Set<Map.Entry<String, Integer>> s = hm.entrySet();
         Iterator<Entry<String, Integer>> itr = s.iterator();
	      
         while(itr.hasNext())
         {
             Map.Entry<String, Integer> m = (Entry<String, Integer>)itr.next();
             System.out.println("Salary of "+m.getKey() + " is "+m.getValue());
         }
     }
 }

Output

{Rohit=6000, James=5000, Daisy=8000, Poonam=7000, Ricky=9000}

After using Iterator ::
Salary of Rohit is 6000
Salary of James is 5000
Salary of Daisy is 8000
Salary of Poonam is 7000
Salary of Ricky is 9000

 

Leave a reply