Use list.associateBy { it.id } when the element is the value and you pick the key, list.associateWith { it.length } when the element is the key, and list.associate { it.id to it.name } when you pick both. A list of pairs becomes a map with toMap(). All of them keep the list order and, on a duplicate key, keep the last value without an error; use groupBy { it.key } to keep every value as a list.
Java turns a list into a map with stream().collect(Collectors.toMap(…)). Kotlin has no streams in the way: the standard library puts the conversion on the collection itself, as a family of associate functions, plus groupBy, partition, joinToString, sumOf and the rest for every other Collectors call. The sections below build a map from a list, from pairs and from two lists, show exactly what a duplicate key does, group and count, map each Java collector to its Kotlin call, and transform a map you already have with mapValues, mapKeys and filterKeys, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.
1associateBy, associateWith and associateRecommended
Three functions cover almost every list-to-map conversion, and the name says which side the lambda produces. associateBy { … } returns the key and keeps the element as the value, the usual way to index objects by an id. Pass a second lambda, associateBy({ key }, { value }), to pick the value as well. associateWith { … } is the mirror image: the element is the key and the lambda returns the value. associate { … } returns a whole Pair, written key to value, so it can do both. The result is a read-only Map; looking up a missing key with map[key] gives null.
data class User(val id: Int, val name: String, val city: String) fun main() { val users = listOf( User(1, "Ann", "Oslo"), User(2, "Bob", "Lima"), User(3, "Cy", "Oslo"), ) // associateBy: the lambda gives the key, the element is the value val byId: Map<Int, User> = users.associateBy { it.id } println(byId[2]) // associateBy with a second lambda picks the value too val nameById = users.associateBy({ it.id }, { it.name }) println(nameById) // associateWith: the element is the key, the lambda gives the value val words = listOf("kotlin", "map", "list") println(words.associateWith { it.length }) // associate: return a Pair (key to value) for each element println(users.associate { it.name to it.city }) // A method reference works as the key selector println(users.associateBy(User::name).keys) // A missing key gives null; getValue() throws instead println(byId[9]?.name ?: "no user 9") try { byId.getValue(9) } catch (e: NoSuchElementException) { println(e.message) } }
Output
byId[2] is the whole User(id=2, name=Bob, city=Lima), while the two-lambda form stores only the names: {1=Ann, 2=Bob, 3=Cy}. associateWith gives {kotlin=6, map=3, list=4}, and the entries come out in list order, because every associate function builds a LinkedHashMap. byId[9] is null, so the Elvis operator prints no user 9; getValue(9) throws NoSuchElementException with Key 9 is missing in the map.
2Pairs, two lists and toMap()
When the data is already a list of Pairs, toMap() turns it into a map in one call. Two lists of keys and values become pairs with zip, the index becomes a key through withIndex(), and a flat list of alternating keys and values splits with chunked(2). Many older answers write list.map { it to f(it) }.toMap(); it works, but builds a list of pairs first, and associate does the same in one step. For a map you can change, call toMutableMap(), or fill an existing map with the …To variants such as associateWithTo.
fun main() { // A list of pairs becomes a map with toMap() val pairs = listOf("a" to 1, "b" to 2, "c" to 3) val map: Map<String, Int> = pairs.toMap() println(map) // Two lists side by side: zip makes the pairs val keys = listOf("red", "green", "blue") val codes = listOf("#f00", "#0f0", "#00f") println(keys.zip(codes).toMap()) // The index as the key println(keys.withIndex().associate { (i, color) -> i to color }) // A flat list of key, value, key, value val flat = listOf("host", "localhost", "port", "8080") println(flat.chunked(2).associate { (k, v) -> k to v }) // The older form: map { } to pairs, then toMap() println(keys.map { it to it.length }.toMap()) // A MutableMap: toMutableMap(), or associate into an existing map val counts = pairs.toMap().toMutableMap() counts["d"] = 4 println(counts) val target = mutableMapOf("z" to 26) keys.associateWithTo(target) { it.length } println(target) // And back: a Map to a List println(map.toList()) println(map.map { (k, v) -> "$k=$v" }) }
Output
zip pairs the lists by position, giving {red=#f00, green=#0f0, blue=#00f}; if one list is longer, the extra elements are dropped. The (i, color) and (k, v) in the lambdas are destructuring, which works on IndexedValue and on a list. The older map plus toMap() line gives the same result as associateWith would. associateWithTo adds to the map you pass, so z=26 stays first. Going back, toList() gives pairs, [(a, 1), (b, 2), (c, 3)], and map on a map gives a list of whatever the lambda returns.
3Duplicate keys: the last one wins
A map holds one value per key, so when two elements produce the same key, one of them is lost. Kotlin's associate functions and toMap() keep the last value and say nothing. That is the opposite of Java's Collectors.toMap, which throws. Decide which behavior you want: keep the first with distinctBy, keep all of them with groupBy, merge them yourself, or check for duplicates and fail.
import java.util.stream.Collectors data class User(val id: Int, val name: String, val city: String) fun main() { val users = listOf( User(1, "Ann", "Oslo"), User(2, "Bob", "Lima"), User(3, "Cy", "Oslo"), ) // Two users in Oslo: the last one wins, without any error val byCity = users.associateBy({ it.city }, { it.name }) println(byCity) println("${users.size} users, ${byCity.size} keys") // First one wins: drop later duplicates before building the map println(users.distinctBy { it.city }.associateBy({ it.city }, { it.name })) // Keep every value: groupBy gives a list per key println(users.groupBy({ it.city }, { it.name })) // Merge the values yourself: join the names per city val merged = users.groupBy({ it.city }, { it.name }) .mapValues { (_, names) -> names.joinToString("+") } println(merged) // Find the duplicates when keys must be unique val dupes = users.groupingBy { it.city }.eachCount().filterValues { it > 1 } println("duplicate keys: ${dupes.keys}") // Java's Collectors.toMap throws on a duplicate key instead try { users.stream().collect(Collectors.toMap({ it.city }, { it.name })) } catch (e: IllegalStateException) { println(e.message) } }
Output
Three users go in and two keys come out: {Oslo=Cy, Lima=Bob}. Ann is gone, replaced by Cy, though Oslo keeps the position where it was first inserted. distinctBy keeps the first user per city, so Ann stays ({Oslo=Ann, Lima=Bob}), and groupBy loses nothing: {Oslo=[Ann, Cy], Lima=[Bob]}. To make duplicates an error, count the keys as shown, or compare map.size with list.size in a require. The Java collector, which you can still call on a Kotlin list, throws IllegalStateException with Duplicate key Oslo (attempted merging values Ann and Cy).
4Group, count and split: groupBy, groupingBy, partition
groupBy { … } is Kotlin's Collectors.groupingBy: it returns a Map<K, List<T>>, one list per key, in the order the keys first appear. For a count or a sum per key, groupingBy { … } (note the ing) returns a lazy Grouping that you finish with eachCount(), fold or reduce, without building the lists first. The other common pattern is groupBy followed by mapValues. partition { … } splits a list in two by a condition and returns a Pair of lists, which you can destructure.
data class Order(val customer: String, val item: String, val total: Int) fun main() { val orders = listOf( Order("Ann", "book", 12), Order("Bob", "pen", 3), Order("Ann", "lamp", 40), Order("Cy", "book", 12), Order("Bob", "desk", 150), ) // groupBy: Map<K, List<T>>, like Collectors.groupingBy val byCustomer = orders.groupBy { it.customer } println(byCustomer.mapValues { (_, list) -> list.map { it.item } }) // groupingBy + eachCount: like groupingBy(..., counting()) println(orders.groupingBy { it.item }.eachCount()) // A sum per key: groupingBy + fold, or groupBy + sumOf println(orders.groupingBy { it.customer }.fold(0) { sum, o -> sum + o.total }) println(byCustomer.mapValues { (_, list) -> list.sumOf { it.total } }) // The biggest order per customer println(byCustomer.mapValues { (_, list) -> list.maxOf { it.total } }) // partition: two lists, like Collectors.partitioningBy val (big, small) = orders.partition { it.total >= 40 } println("big: ${big.map { it.item }}, small: ${small.map { it.item }}") }
Output
The groups keep the order of first appearance, Ann, Bob, Cy, and each list keeps the original order. eachCount() gives {book=2, pen=1, lamp=1, desk=1}, a word-frequency count in one line. Both ways of summing print {Ann=52, Bob=153, Cy=12}; fold on the Grouping skips the lists, which matters only for large inputs. Unlike Java's partitioningBy, which returns a Map<Boolean, List<T>>, partition returns the matching list first: [lamp, desk], then the rest.
5Java Stream.collect equivalents
Each Collectors call has a direct function on Kotlin collections, so there is no stream() and no collect(): joining is joinToString, summingInt is sumOf, counting is count, maxBy is maxByOrNull, which returns a nullable value instead of an Optional. The functions on a List are eager: each step builds a new list. For a long chain on a big list, or when you only need the first match, call asSequence() first; a Sequence is lazy like a Stream.
data class Order(val customer: String, val item: String, val total: Int) fun main() { val orders = listOf( Order("Ann", "book", 12), Order("Bob", "pen", 3), Order("Ann", "lamp", 40), Order("Cy", "book", 12), ) // Collectors.joining(", ", "[", "]") println(orders.joinToString(", ", "[", "]") { it.item }) // Collectors.summingInt / averagingInt / counting println(orders.sumOf { it.total }) println(orders.map { it.total }.average()) println(orders.count { it.customer == "Ann" }) // Collectors.maxBy returns Optional; Kotlin returns T? println(orders.maxByOrNull { it.total }?.item) println(orders.minOf { it.total }) // Collectors.toSet, and mapping(...) into a sorted set println(orders.map { it.item }.toSet()) println(orders.mapTo(sortedSetOf()) { it.customer }) // Collectors.reducing: fold with a start value, or reduce println(orders.fold(0) { acc, o -> acc + o.total }) println(orders.map { it.item }.reduce { a, b -> "$a/$b" }) // Collectors.summarizingInt: no single call, but each part is one val totals = orders.map { it.total } println("min=${totals.min()} max=${totals.max()} sum=${totals.sum()}") // Long chains: asSequence() is lazy, like a Stream val firstBig = orders.asSequence() .filter { it.total > 10 } .map { it.item.uppercase() } .first() println(firstBig) }
Output
joinToString takes the separator, prefix and postfix, plus a lambda for each element, and prints [book, pen, lamp, book]. The total is 67 and the average 16.75; average() always returns a Double. maxByOrNull finds the lamp order, and on an empty list it would return null where Java returns an empty Optional. toSet() drops the second book. In the sequence, first() stops at the first order over 10, so map runs once and prints BOOK.
6Transform a map: mapValues, mapKeys, filterKeys
Once you have a map, the same style continues. mapValues keeps the keys and replaces each value, mapKeys keeps the values and replaces each key, and filterKeys, filterValues and filter drop entries. Each lambda receives a Map.Entry, which you can destructure as (key, value), and use _ for the half you don't need. To swap keys and values, call associate on entries. Each of these returns a new read-only map; on a MutableMap, replaceAll and entries.removeIf { … } change it in place.
fun main() { val prices = mapOf("apple" to 120, "pear" to 90, "fig" to 300) // mapValues: same keys, new values println(prices.mapValues { (_, cents) -> cents / 100.0 }) // mapKeys: same values, new keys println(prices.mapKeys { (name, _) -> name.uppercase() }) // filterKeys, filterValues, and filter on both println(prices.filterKeys { it.length > 3 }) println(prices.filterValues { it > 100 }) println(prices.filter { (name, cents) -> name.startsWith("f") || cents < 100 }) // Swap keys and values: entries.associate println(prices.entries.associate { (name, cents) -> cents to name }) // map { } on a Map gives a List, not a Map println(prices.map { (name, cents) -> "$name: $cents" }) // If two new keys collide, mapKeys keeps the last value println(prices.mapKeys { (_, cents) -> if (cents >= 100) "big" else "small" }) // Add, remove, sort: each returns a new Map println(prices + ("kiwi" to 50)) println(prices - "pear") println(prices.toSortedMap()) println(prices.entries.sortedBy { it.value }.associate { it.toPair() }) }
Output
mapValues turns cents into {apple=1.2, pear=0.9, fig=3.0} and mapKeys upper-cases the names. Swapping gives {120=apple, 90=pear, 300=fig}; with repeated values, the last one would win, as in section 3. The collision line is the gotcha: apple and fig both become big, and the result {big=300, small=90} keeps only fig's price. toSortedMap() sorts by key, while sorting by value needs entries.sortedBy and a rebuild with associate, giving {pear=90, apple=120, fig=300}.
7Which should you use?
| Function | Gives | Duplicate keys | Java equivalent |
|---|---|---|---|
| list.associateBy { it.id } | Map<K, T> | Last wins | Collectors.toMap(f, identity()) |
| list.associateWith { f(it) } | Map<T, V> | Last wins | Collectors.toMap(identity(), f) |
| list.associate { k to v } | Map<K, V> | Last wins | Collectors.toMap(k, v) |
| pairs.toMap() | Map<K, V> | Last wins | Collectors.toMap on entries |
| list.groupBy { it.key } | Map<K, List<T>> | All kept | Collectors.groupingBy |
| list.groupingBy { k }.eachCount() | Map<K, Int> | Counted | groupingBy(k, counting()) |
| list.partition { test } | Pair<List<T>, List<T>> | Not a map | Collectors.partitioningBy |
| map.mapValues { … }, mapKeys { … } | Map | mapKeys: last wins | Stream over entrySet() |
Frequently asked questions
What is the difference between associate, associateBy and associateWith?
They differ in what the lambda returns. associateBy { it.id } returns the key and keeps the element as the value. associateWith { it.length } uses the element as the key and the lambda gives the value. associate { it.id to it.name } returns a Pair, so you choose both. When the element is either the key or the value, prefer associateBy or associateWith: they read better and skip creating a Pair per element.
What happens to duplicate keys when converting a list to a map?
The last value wins and no error is raised: three users in two cities give a map with two entries, and the key keeps the position where it first appeared. Java's Collectors.toMap throws IllegalStateException (Duplicate key Oslo (attempted merging values Ann and Cy)) instead. Use distinctBy first to keep the first value, groupBy to keep them all, or compare map.size with list.size to fail.
Does the map keep the order of the list?
Yes. associateBy, associateWith, associate, groupBy and mapValues build a java.util.LinkedHashMap, and toMap() keeps the order too, so iterating the map follows the order in which keys were first inserted. A duplicate key replaces the value but keeps its first position. For key order instead, call toSortedMap(), which returns a java.util.TreeMap.
How do I get a MutableMap from a list?
Call toMutableMap() on the result, for example list.associateBy { it.id }.toMutableMap(), or pass your own map to the To variants: list.associateByTo(mutableMapOf()) { it.id } and associateWithTo add entries to the map you give them. The plain functions return a read-only Map type, so map[key] = value on it fails to compile with No 'set' operator method providing array access.
Is there a Kotlin equivalent of Java streams?
Kotlin collections have the stream operations built in (filter, map, groupBy, sumOf, joinToString), so you call them directly without stream() or collect(). They are eager, building a new list per step. For lazy evaluation like a Stream, call asSequence() at the start of the chain and finish with toList(), first() or another terminal call. Java streams still work on Kotlin lists if you are porting code.
How do I convert a Map back to a List?
Use map.toList() for a list of pairs, map.keys.toList() or map.values.toList() for one side, or map.map { (k, v) -> "$k=$v" } to turn each entry into anything you like. mapOf("a" to 1, "b" to 2).toList() gives [(a, 1), (b, 2)].
How do I sort a map by its values?
A map has no sort function of its own for values. Sort the entries and rebuild it: map.entries.sortedBy { it.value }.associate { it.toPair() }. The result is a LinkedHashMap in that order. toSortedMap() sorts by key and returns a TreeMap. Use sortedByDescending for the largest values first.
Run it yourself
Open any of these in the full Kotlin editor to tweak, run and share.
Kotlin playground