← All languages
Kotlin function of the day
Random

hashMapOf

Return a new HashMap with the given key/value pairs.

Description

The hashMapOf() top-level function returns a new java.util.HashMap<K, V> populated with the supplied Pair entries. Like arrayListOf(), it is the most explicit way to construct that specific Java-compatible map type.

The returned map is mutable: entries can be added, removed, and updated. The HashMap class does not preserve insertion order; for that, use linkedMapOf(). For natural-key ordering, use sortedMapOf().

For most pure-Kotlin code, prefer mutableMapOf() which returns a MutableMap<K, V> backed by a LinkedHashMap, preserving iteration order. Use hashMapOf() only when the concrete HashMap type is required for Java interop or when you specifically want unordered iteration.

Arguments

NameDescriptionOptional
pairs Pair instances providing initial key-value pairs. Yes

Example

val ages = hashMapOf("Alice" to 30, "Bob" to 25)
ages["Charlie"] = 35

val empty = hashMapOf<String, Int>()

Reference