If I have an object implementing the Map interface in Java and I wish to iterate over every pair contained within it, what is the most efficient way of going through the map?
If efficiency of looping the keys is a priority for your app, then choose a Map
implementation that maintains the keys in your desired order.
Will the ordering of elements depend on the specific map implementation that I have for the interface?
Yes, absolutely.
Map
implementations promise a certain iteration order, others do not.Map
maintain different ordering of the key-value pairs. See this table I created summarizing the various Map
implementations bundled with Java 11. Specifically, notice the iteration order column. Click/tap to zoom.
You can see there are four Map
implementations maintaining an order:
TreeMap
ConcurrentSkipListMap
LinkedHashMap
EnumMap
NavigableMap
interfaceTwo of those implement the NavigableMap
interface: TreeMap
& ConcurrentSkipListMap
.
The older SortedMap
interface is effectively supplanted by the newer NavigableMap
interface. But you may find 3rd-party implementations implementing the older interface only.
If you want a Map
that keeps its pairs arranged by the “natural order” of the key, use TreeMap
or ConcurrentSkipListMap
. The term “natural order” means the class of the keys implements Comparable
. The value returned by the compareTo
method is used for comparison in sorting.
If you want to specify a custom sorting routine for your keys to be used in maintaining a sorted order, pass a Comparator
implementation appropriate to the class of your keys. Use either TreeMap
or ConcurrentSkipListMap
, passing your Comparator
.
If you want the pairs of your map to be kept in their original order in which you inserted them into the map, use LinkedHashMap
.
If you are using an enum such as DayOfWeek
or Month
as your keys, use the EnumMap
class. Not only is this class highly optimized to use very little memory and run very fast, it maintains your pairs in the order defined by the enum. For DayOfWeek
, for example, the key of DayOfWeek.MONDAY
will be first found when iterated, and the key of DayOfWeek.SUNDAY
will be last.
In choosing a Map
implementation, also consider:
Collections::synchronizedMap
(less preferable). Both of these considerations are covered in the graphic table above.