How to keep the insertion order with Java LinkedHashMap?



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
Updated on: 2019-07-30T22:30:25+05:30

233 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements