LinkedHashMap
In a HashMap
, the order entries are added is not maintained—it is lost when they are put into the table. But with LinkedHashMap
, a linked list maintains the order.
To ensure we can access elements in the order we add them, LinkedHashMap
is a good alternative to HashMap
. It still has constant time lookup, but just has some overhead.
Let us examine this program. We import the LinkedHashMap
in the same way we would import HashMap
. We use diamond inference syntax in the same way as well.
LinkedHashMap
. Then we use entrySet()
to loop over them.System.out.println
.entrySet
. The collection never forgot the ordering.import java.util.LinkedHashMap; import java.util.Map.Entry; public class Program { public static void main(String[] args) { // Add 3 entries to a LinkedHashMap. LinkedHashMap<String, Integer> values = new LinkedHashMap<>(); values.put("bird", 10); values.put("frog", 20); values.put("snake", 25); // For LinkedHashMap, we can loop over the items in the order they were added. // ... A linked list keeps track of the order as we add them. for (Entry<String, Integer> pair : values.entrySet()) { System.out.println(pair.getKey() + "/" + pair.getValue()); } } }bird/10 frog/20 snake/25
HashMap
loopConsider this version of the program. It uses HashMap
instead of LinkedHashMap
. The items are added in a certain order, and then loops over the entries.
HashMap
(unlike LinkedHashMap
) they are looped over in a different order. This program shows the change.import java.util.HashMap; import java.util.Map.Entry; public class Program { public static void main(String[] args) { HashMap<String, Integer> values = new HashMap<>(); values.put("bird", 10); values.put("frog", 20); values.put("snake", 25); for (Entry<String, Integer> pair : values.entrySet()) { System.out.println(pair.getKey() + "/" + pair.getValue()); } } }frog/20 bird/10 snake/25
The LinkedHashMap
is an ideal replacement for HashMap
when we need to maintain the order of items we put into the table. If ordering is needed, prefer LinkedHashMap
.
HashMap
is better because it will be slightly faster in most programs.The LinkedHashMap
is a special kind of HashMap
. It enforces a linked list data structure where the order is maintained. This helps if the time of an addition is important.
For most programs, HashMap
is a better choice as it is simpler. It also has less conceptual complexity (it omits the "Linked" part). It is important to choose the correct collection.