LinkedHashMap Class

LinkedHashMap

LinkedHashMap will keep the order in which the elements are inserted into it. If you will be adding and removing elements a lot, it will be better to use HashMap, because LinkedHashMap will be slower to do those operations. But, you can iterate faster using LinkedHashMap. So, if you will be iterating heavily, it may be a good idea to use this. It is exactly same as HashMap except the following differences

Capture 19
package com.ashok.collections;

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

/**
 * 
 * @author ashok.mariyala
 *
 */
public class MyHashMap {
   public static void main(String[] args) {
      LinkedHashMap hMap = new LinkedHashMap ();
      hMap.put("Ashok", 500);
      hMap.put("Vinod", 800);
      hMap.put("Dillesh", 700);
      hMap.put("Naresh", 500);
      System.out.println(hMap);
      System.out.println(hMap.put("Ashok", 1000));
      Set s = hMap.keySet();
      System.out.println(s);
      Collection c = hMap.values();
      System.out.println(c);
      Set s1 = hMap.entrySet();
      System.out.println(s1);
      Iterator itr = s1.iterator();
      while (itr.hasNext()) {
         Map.Entry m1 = (Map.Entry) itr.next();
         System.out.println(m1.getKey() + "......" + m1.getValue());
         if (m1.getKey().equals("Ashok")) {
            m1.setValue(1500);
         }
      }
      System.out.println(hMap);
   }
}

Output

{Ashok=500, Vinod=800, Dillesh=700, Naresh=500}
500
[Ashok, Vinod, Dillesh, Naresh]
[1000, 800, 700, 500]
[Ashok=1000, Vinod=800, Dillesh=700, Naresh=500]
Ashok......1000
Vinod......800
Dillesh......700
Naresh......500
{Ashok=1500, Vinod=800, Dillesh=700, Naresh=500}
LinkedHashMap Class

Scroll to top