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
- LinkedHashMap implements Map interface and extends HashMap class.
- LinkedHashMap maintains insertion order, so when you will be able to access elements in the order they were inserted like ArrayList.
- LinkedHashMap maintains doubly Linked list to maintain insertion order.
Example:
LinkedHashMapMain.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 29 |
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:
1 2 3 4 5 6 7 8 9 |
----------------------------- 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 ----------------------------- |