LinkedHashMap example in Java
LinkedHashMap is part of the java.util package and it extends the HashMap, so it has all the properties of HashMap. LinkedHashMap maintains the order of insertion of the elements, hence when we iterate a LinkedHashMap we get the elements in the order in which they were inserted.
LinkedHashMap maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted. In this post lets see LinkedHashMap example in Java.
LinkedHashMap example in Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | package com.kscodes.collections; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; public class LinkedHashMapExample { public static void main(String args[]) { // Create a linkedHashMap and add elements to it. LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<>(); linkedHashMap.put("Z", "Zebra"); linkedHashMap.put("A", "Apple"); linkedHashMap.put("D", "Dog"); linkedHashMap.put("B", "Ball"); // Display the Elements by Iterating over the linkedHashMap Set<Entry<String, String>> set = linkedHashMap.entrySet(); Iterator<Entry<String, String>> iterator = set.iterator(); while (iterator.hasNext()) { Map.Entry mapEntry = (Map.Entry) iterator.next(); System.out.print(mapEntry.getKey() + " : " + mapEntry.getValue()); System.out.println(""); } } } |
Output
From the Output you will be able to see that when we iterate the LinkedHashMap, it returns the elements in order exactly as they were inserted.