How to convert List to Map in Kotlin?

kotlin list to map groupby
kotlin flatten list of maps
kotlin map transform example
kotlin groupby
kotlin convert map to hashmap
kotlin stream map
kotlin list to map with index
convert string to map in kotlin

For example I have a list of strings like:

val list = listOf("a", "b", "c", "d")

and I want to convert it to a map, where the strings are the keys.

I know I should use the .toMap() function, but I don't know how, and I haven't seen any examples of it.

You have two choices:

The first and most performant is to use associateBy function that takes two lambdas for generating the key and value, and inlines the creation of the map:

val map = friends.associateBy({it.facebookId}, {it.points})

The second, less performant, is to use the standard map function to create a list of Pair which can be used by toMap to generate the final map:

val map = friends.map { it.facebookId to it.points }.toMap()

How to convert List to Map in Kotlin?, From List to Map with associateBy function. Returns a Map containing the values provided by valueTransform and indexed by keySelector functions applied to elements of the given collection. IterableSequenceElements. associate { newKey to newValue } //Output => Map {newKey : newValue ,} From List to Map with associate function. With Kotlin 1.3, List has a function called associate. associate has the following declaration: fun <T, K, V> Iterable<T>.associate(transform: (T) -> Pair<K, V>): Map<K, V> Returns a Map containing key-value pairs provided by transform function applied to elements of the given collection. Usage:

From List to Map with associate function

With Kotlin 1.3, List has a function called associate. associate has the following declaration:

fun <T, K, V> Iterable<T>.associate(transform: (T) -> Pair<K, V>): Map<K, V>

Returns a Map containing key-value pairs provided by transform function applied to elements of the given collection.

Usage:

class Person(val name: String, val id: Int)

fun main() {
    val friends = listOf(Person("Sue Helen", 1), Person("JR", 2), Person("Pamela", 3))
    val map = friends.associate({ Pair(it.id, it.name) })
    //val map = friends.associate({ it.id to it.name }) // also works

    println(map) // prints: {1=Sue Helen, 2=JR, 3=Pamela}
}    

From List to Map with associateBy function

With Kotlin, List has a function called associateBy. associateBy has the following declaration:

fun <T, K, V> Iterable<T>.associateBy(keySelector: (T) -> K, valueTransform: (T) -> V): Map<K, V>

Returns a Map containing the values provided by valueTransform and indexed by keySelector functions applied to elements of the given collection.

Usage:

class Person(val name: String, val id: Int)

fun main() {
    val friends = listOf(Person("Sue Helen", 1), Person("JR", 2), Person("Pamela", 3))
    val map = friends.associateBy(keySelector = { person -> person.id }, valueTransform = { person -> person.name })
    //val map = friends.associateBy({ it.id }, { it.name }) // also works

    println(map) // prints: {1=Sue Helen, 2=JR, 3=Pamela}
}

Kotlin: How to convert list to map with list?, Code. fun main(args: Array<String>) { data class Combine(val alpha: String, val num: Int) val list = arrayListOf(Combine("a", 1), Combine("b", 2),  The standard way to convert a List to a Map is with the associate() function. It returns a Map containing key-value pairs provided by transform function applied to elements of the given list. In the following example, we will construct a Map from List of Color objects. The Color class contains name and hex field.

You can use associate for this task:

val list = listOf("a", "b", "c", "d")
val m: Map<String, Int> = list.associate { it to it.length }

In this example, the strings from list become the keys and their corresponding lengths (as an example) become the values inside the map.

Collection Transformation Operations, When transforming maps, you have two options: transform keys leaving values In this case, the result List contains the return values of the transformation  Kotlin Program to Convert Map (HashMap) to List In this program, you'll learn different techniques to convert a map to a list in Kotlin.

How to convert list to map in Kotlin, For example, you have a list of strings like: val list = listOf("a", "b", "c", "d"). and you need to convert it to a map, where the strings are the keys. In the tutorial, Grokonez will show you how to convert Kotlin Map to List. Related posts: – Convert Kotlin List to Map ContentsI. Convert Kotlin Map to List1. Basic Method2. Map ObjectII. Practice1. Create model data2. Kotlin programIII. Sourcecode I. Convert Kotlin Map to List 1. Basic Method – Use public fun Map.toList(): List to … Continue reading "Convert Kotlin Map to List"

If you have duplicates in your list that you don't want to lose, you can do this using groupBy.

Otherwise, like everyone else said, use associate/By/With (which in the case of duplicates, I believe, will only return the last value with that key).

An example grouping a list of people by age:

class Person(val name: String, val age: Int)

fun main() {
    val people = listOf(Person("Sue Helen", 31), Person("JR", 25), Person("Pamela", 31))

    val duplicatesKept = people.groupBy { it.age }
    val duplicatesLost = people.associateBy({ it.age }, { it })

    println(duplicatesKept)
    println(duplicatesLost)
}

Results:

{31=[Person@41629346, Person@4eec7777], 25=[Person@3b07d329]}
{31=Person@4eec7777, 25=Person@3b07d329}

Kotlin Program to Convert Map (HashMap) to List, In this program, you'll learn different techniques to convert a map to a list in Kotlin. Kotlin filter List example; Kotlin List reduce(), reduceIndexed(), reduceRight(), reduceRightIndexed() methods example; Kotlin onEach() vs forEach() example; Kotlin List methods – max() maxBy() maxWith() example; Kotlin Distinct() methods of List collection example; Convert Kotlin List to Map; Convert Kotlin Map to List; Kotlin – Convert

Kotlin Program to Convert List (ArrayList) to Array and Vice-Versa, Related Examples. Kotlin Example. Convert Array to Set (HashSet) and Vice-​Versa · Kotlin Example. Convert Map (  Kotlin Program to Convert List (ArrayList) to Array and Vice-Versa In this program, you'll learn to convert a list to an array using toArray() and array to list using asList() in Kotlin.

Kotlin let, run, also, apply, with, is a scoping function wherein the variables declared inside the expression cannot be used outside. I want to convert/map some "data" class objects to similar "data" class objects. Better way to map Kotlin data objects to data objects. Use kotlin no-args

Kotlin transform List with map() methods example » grokonez, mapIndexed(transform: (index: Int, T) -> R): List. Method signature: public inline  How to convert list to map in Kotlin. Two ways to convert list to map in Kotlin, with code examples 31 October 2017 6952 For example, you have a list of strings like:

Comments
  • Your question needs clarification please. You can't have just a list of keys to create a map. From your own answer you show a list of something else so your question should be adjusted to match and be a realistic question. I made a suggested edit.
  • thank you. is it faster because it creates a map, and not converts a list of pairs to a map, like in my example?
  • @lordScone Exactly, the allocations of Pair instances might be very costly for big collections
  • What's the difference between associate and associateBy? Would I want to prefer to use one over the other, seeing that they produce the same result?