LinkedHashMap in java with example

In this post, we will see about LinkedHashMap in java. LinkedHashMap is same as HashMap except that it maintains insertion order.

Some points about LinkedHashMap
  1. LinkedHashMap implements Map interface and extends HashMap class.
  2. LinkedHashMap maintains insertion order, so when you will be able to access elements in the order they were inserted like ArrayList.
  3. LinkedHashMap maintains doubly Linked list to maintain insertion order.

Example:

LinkedHashMapMain.java
package org.arpit.java2blog;

import java.util.LinkedHashMap;

public class LinkedHashMapMain {

 public static void main(String args[])
 {
  // LinkedHashMap with Country as key and capital as value
 // LinkedHashMap maintains insertion order  
  LinkedHashMap<String,String> countryCapitalMap=new LinkedHashMap<String,String>();
  countryCapitalMap.put("India","Delhi");
  countryCapitalMap.put("Japan","Tokyo");
  countryCapitalMap.put("France","Paris");
  countryCapitalMap.put("Russia","Moscow");

  System.out.println("-----------------------------");
  // Iterating Using keySet() and for each loop
  System.out.println("Iterating Using keySet() and for each loop");
  for (String countryKey:countryCapitalMap.keySet()) {
   System.out.println("Country:"+ countryKey +" and  Capital:"+countryCapitalMap.get(countryKey));

  }
  System.out.println("-----------------------------");
}

}

If you may iterate LinkedHashMap in multiple ways.
When you run above program, you will get below output:
-----------------------------
Iterating Using keySet() and for each loop
Country:India and  Capital:Delhi
Country:Japan and  Capital:Tokyo
Country:France and  Capital:Paris
Country:Russia and  Capital:Moscow
-----------------------------

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012