[java] How do I efficiently iterate over each entry in a Java Map?

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.

  • Some Map implementations promise a certain iteration order, others do not.
  • Different implementations of 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.

Table of map implementations in Java 11, comparing their features

You can see there are four Map implementations maintaining an order:

  • TreeMap
  • ConcurrentSkipListMap
  • LinkedHashMap
  • EnumMap

NavigableMap interface

Two 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.

Natural order

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.

Custom order

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.

Original insertion order

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.

Enum-definition order

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.

Other considerations

In choosing a Map implementation, also consider:

  • NULLs. Some implementations forbid/accept a NULL as key and/or value.
  • Concurrency. If you are manipulating the map across threads, you must use an implementation that supports concurrency. Or wrap the map with Collections::synchronizedMap (less preferable).

Both of these considerations are covered in the graphic table above.

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to dictionary

JS map return object python JSON object must be str, bytes or bytearray, not 'dict Python update a key in dict if it doesn't exist How to update the value of a key in a dictionary in Python? How to map an array of objects in React C# Dictionary get item by index Are dictionaries ordered in Python 3.6+? Split / Explode a column of dictionaries into separate columns with pandas Writing a dictionary to a text file? enumerate() for dictionary in python

Examples related to collections

Kotlin's List missing "add", "remove", Map missing "put", etc? How to unset (remove) a collection element after fetching it? How can I get a List from some class properties with Java 8 Stream? Java 8 stream map to list of keys sorted by values How to convert String into Hashmap in java How can I turn a List of Lists into a List in Java 8? MongoDB Show all contents from all collections Get nth character of a string in Swift programming language Java 8 Distinct by property Is there a typescript List<> and/or Map<> class/library?

Examples related to iteration

Is there a way in Pandas to use previous row value in dataframe.apply when previous value is also calculated in the apply? How to loop over grouped Pandas dataframe? How to iterate through a list of dictionaries in Jinja template? How to iterate through an ArrayList of Objects of ArrayList of Objects? Ways to iterate over a list in Java Python list iterator behavior and next(iterator) How to loop through an array containing objects and access their properties recursion versus iteration What is the perfect counterpart in Python for "while not EOF" How to iterate over a JavaScript object?