How to keep the insertion order with Java LinkedHashMap?

Java 8Object Oriented ProgrammingProgramming

To keep the insertion order with LinkedHashMap, use Iterator. Let us first create a HashMap and add elements to it −

LinkedHashMap<String, String>lHashMap = new LinkedHashMap<String, String>();
lHashMap.put("1", "A");
lHashMap.put("2", "B");
lHashMap.put("3", "C");
lHashMap.put("4", "D");
lHashMap.put("5", "E");
lHashMap.put("6", "F");
lHashMap.put("7", "G");
lHashMap.put("8", "H");
lHashMap.put("9", "I");

Now, get the values with the values() method. Iterate through the elements and display them −

Collection collection = lHashMap.values();
Iterator i = collection.iterator();
while (i.hasNext()) {
   System.out.println(i.next());
}

Example

 Live Demo

import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
public class Demo {
   public static void main(String[] args) {
      LinkedHashMap<String, String>lHashMap = new LinkedHashMap<String, String>();
      lHashMap.put("1", "A");
      lHashMap.put("2", "B");
      lHashMap.put("3", "C");
      lHashMap.put("4", "D");
      lHashMap.put("5", "E");
      lHashMap.put("6", "F");
      lHashMap.put("7", "G");
      lHashMap.put("8", "H");
      lHashMap.put("9", "I");
      Collection collection = lHashMap.values();
      Iterator i = collection.iterator();
      while (i.hasNext()) {
         System.out.println(i.next());
      }
   }
}

Output

A
B
C
D
E
F
G
H
I
raja
Updated on 30-Jul-2019 22:30:25

Advertisements