HashMap Example in Java

HashMap is used for Key-Value concepts. when  we require to store values based on Key then HashMap is for You !

About HashMap :
  • HashMap is class which extends AbstractMap and Implements Map Interface
  • HashMap does not maintain insertion order
  • Allows null as Key and Values also - No Exception is thrown
  • Contains unique elements Only

If You observe output of HashMap example as below,  Output is not same in sequence we inserted elements because HashMap does not maintain Insertion Order while LinkedHashMap does.

Java HashMap Example :
package com.anuj.basic;

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

/**
 * 
 * @author Anuj
 * Does not maintain Insertion Order
 * Allow Null
 */
public class HashMapOperations {

 public static void main(String[] args) {
  HashMap hashMap = new HashMap();
  
  hashMap.put("Anuj","1");
  hashMap.put("Zvika","2");
  hashMap.put("David", "3");
  hashMap.put("David", "3");
  hashMap.put(null,null);
  
  Set set = hashMap.entrySet();
  Iterator iterator = set.iterator();
  
  while(iterator.hasNext()){
   Map.Entry entry = (Map.Entry)iterator.next();
   System.out.println("Key:"+entry.getKey() + " Value:"+entry.getValue());
  }
 }

}


Output :
Key:null Value:null
Key:David Value:3
Key:Anuj Value:1
Key:Zvika Value:2

No comments:

Post a Comment