LinkedHashMap Example in Java

LinkedHashMap is used for Key-Value concepts. when we require to store values based on Key then LinkedHashMap is for You !But It maintains insertion order while HashMap does not.

About LinkedHashMap:
  • It extends HashMap class and Implements Map Interface
  • It maintain insertion order
  • Allows null as Key and Values also
  • Contains unique elements Only
If You observe output of LinkedHashMap example as below, Output is same in sequence we inserted elements because LinkedHashMap does maintain Insertion Order while HashMap does not.

Java LinkedHashMap Example :
package com.anuj.basic;

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

/**
 * 
 * @author Anuj
 * Maintain Insertion Order
 * Allow Null
 */
public class LinkedHashMapOperations {

 public static void main(String[] args) {
  LinkedHashMap hashMap = new LinkedHashMap();
  
  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:Anuj Value:1
Key:Zvika Value:2
Key:David Value:3
Key:null Value:null

No comments:

Post a Comment