skip to content

When you call mapOf(...) or setOf(...) in Kotlin, what concrete JVM type backs the result, and what does that mean for iteration order?

level: juniorimportance: must knowfreq 70%

answer

  1. mapOf -> LinkedHashMap
  2. setOf -> LinkedHashSet
  3. insertion order, not sorted
  4. hashMapOf = unspecified order
  5. sortedMapOf = TreeMap

basics

~10 s

Kotlin's default maps and sets keep elements in the order you inserted them. They are backed by LinkedHashMap and LinkedHashSet, so looping over them gives you items in insertion order.

solid answer

~30 s

On the JVM, mapOf()/mutableMapOf() create a LinkedHashMap, and setOf()/mutableSetOf() create a LinkedHashSet. The key consequence is deterministic insertion-order iteration: entries come out in the order they were added, not sorted and not hash-bucket order. This differs from a plain HashMap/HashSet, whose iteration order is unspecified. It also differs from sortedMapOf()/sortedSetOf() (TreeMap/TreeSet, key-sorted) and linkedMapOf()/linkedSetOf() (explicit LinkedHashMap/Set). Empty calls like emptyMap()/setOf() may return a shared singleton, but any non-empty default still preserves insertion order. Relying on this is safe for building stable output (e.g., JSON, UI lists) without an extra sort.

code

kotlin · 5 lines
kotlin
val ordered = mapOf("x" to 1, "a" to 2)
println(ordered.keys.toList()) // [x, a]

val hashed = hashMapOf("x" to 1, "a" to 2)
println(hashed.keys.toList()) // order unspecified

go deeper

for a junior

Knows defaults preserve insertion order and names LinkedHashMap/LinkedHashSet.

for a middle

Contrasts with hashMapOf (unspecified) and sortedMapOf (TreeMap), and knows update-keeps-position.

for a senior

Notes the guarantee is implementation/stdlib-level, not the interface contract, and picks the factory deliberately for serialization determinism.

for a principal

Reasons about cross-JVM/version stability, when to depend on order vs sort explicitly, and the cost trade-offs of LinkedHashMap's extra linked list.

## What backs the defaults Kotlin doesn't have its own collection runtime on the JVM — it reuses the Java collections. The standard factory functions map to concrete classes: - `mapOf(...)`, `mutableMapOf(...)` -> **`java.util.LinkedHashMap`** - `setOf(...)`, `mutableSetOf(...)` -> **`java.util.LinkedHashSet`** - `listOf(...)`, `mutableListOf(...)` -> `ArrayList` `LinkedHashMap`/`LinkedHashSet` are hash tables **plus** a doubly-linked list threading the entries in **insertion order**. So lookups stay O(1) average like a `HashMap`, but iteration is deterministic. ## Why insertion order matters ```kotlin val m = mapOf("b" to 1, "a" to 2, "c" to 3) println(m.keys) // [b, a, c] -> insertion order, NOT sorted val s = setOf(3, 1, 2, 1) println(s) // [3, 1, 2] -> first occurrence wins, order preserved ``` Contrast with the alternatives: - **`HashMap`/`HashSet`** (via `hashMapOf()`/`hashSetOf()`): iteration order is **unspecified** and can change between runs/JVMs. - **`sortedMapOf()`/`sortedSetOf()`** (TreeMap/TreeSet): iterate in **key/natural order**, O(log n) operations. - **`linkedMapOf()`/`linkedSetOf()`**: explicitly the same `LinkedHashMap`/`LinkedHashSet` you already get by default. ## Practical impact Because defaults are insertion-ordered, you can build a map/set in a meaningful sequence and serialize or render it without an extra sort step, and tests are deterministic. Re-inserting an existing key with `put` **updates the value but keeps the original position**; removing then re-adding moves it to the end. ## Caveat This is a JVM/stdlib implementation guarantee documented for these factories; it is **not** part of the abstract `Map`/`Set` interface contract. Code that depends on order should still use the factory that promises it, not just any `Map`.

  • If you put() a key that already exists, does its iteration position change?
    No. Updating an existing key keeps its original insertion position; only the value changes. Removing and re-adding moves it to the end.
  • How would you get key-sorted iteration instead?
    Use sortedMapOf()/sortedSetOf() (TreeMap/TreeSet), or call .toSortedMap()/.toSortedSet(), or sort the keys before iterating.

A LinkedHashMap is a hash table wearing a guest book: O(1) lookup, but it also records the order people arrived.

saying these in an interview costs you the question

  • Claiming mapOf returns a plain HashMap with random order
  • Saying default maps are sorted by key
  • Believing iteration order is part of the Map interface contract
  • Confusing LinkedHashMap with a TreeMap

context