Java — Which Map implementation maintains iteration order of an existing Map?

Java Programming Objects and Collections Difficulty: Medium
Choose an option
  • A
    TreeMap
  • B
    HashMap
  • C
    LinkedHashMap
  • D
    The answer depends on the implementation of the existing instance.

Answer

Correct Answer: LinkedHashMap

Explanation

Introduction / Context:This question tests knowledge of different Map implementations in Java and their ordering characteristics.

Concept / Approach:

  • HashMap → no ordering guarantee.
  • TreeMap → natural or custom comparator order, not iteration order.
  • LinkedHashMap → maintains insertion order or access order.

Step-by-Step Reasoning:

If you want the iteration order of an existing Map to be preserved, use LinkedHashMap and construct it with the existing Map.

Why Other Options Are Wrong:TreeMap re-sorts keys, HashMap randomizes order, and "depends on implementation" is too vague.

Final Answer:LinkedHashMap

Discussion & Comments
No comments yet. Be the first to comment!
Join Discussion