How to convert List to Map in Kotlin using Kotlin Library

There are a few ways to convert a List to a Map in Kotlin by the Kotlin Library. In this post, we will be discussing, how we can convert List to Map using Kotlin Library.

Using associate()

data class CourseList(val id :String, val courseName :String)


fun main(){

    val myCourseList = listOf(
        CourseList("1", "Android"),
        CourseList("2", "Kotlin"),
        CourseList("3","Java"),
        CourseList("4","C"),
        CourseList("5","C++")
    )

    println("list converted by using associate")
    val myCourseMap : Map<String, String> = myCourseList.associate {
        Pair(it.id, it.courseName)
    }

    println(myCourseMap)
}
list converted by using associate
{1=Android, 2=Kotlin, 3=Java, 4=C, 5=C++}

Using associateBy()

data class CourseList(val id :String, val courseName :String)

fun main(){

    val myCourseList = listOf(
        CourseList("1", "Android"),
        CourseList("2", "Kotlin"),
        CourseList("3","Java"),
        CourseList("4","C"),
        CourseList("5","C++")
    )

    println("list converted by using associateBy")
    val myCourseMap2 : Map<String, String> = myCourseList.associateBy(
        {it.id}, {it.courseName}
    )
    println(myCourseMap2)
}
list converted by using associateBy
{1=Android, 2=Kotlin, 3=Java, 4=C, 5=C++}

Using toMap()

data class CourseList(val id :String, val courseName :String)

fun main(){

    val myCourseList = listOf(
        CourseList("1", "Android"),
        CourseList("2", "Kotlin"),
        CourseList("3","Java"),
        CourseList("4","C"),
        CourseList("5","C++")
    )

    println("list converted by using toMap")
    val myCourseMap3 : Map<String, String> = myCourseList.map {
        it.id to it.courseName
    }.toMap()

    println(myCourseMap3)
}
list converted by using toMap
{1=Android, 2=Kotlin, 3=Java, 4=C, 5=C++}

Techpass Master

Techpass Master is a website for free Android App Development, Java, Kotlin, Jetpack Compose, Firebase, & other tech tips & tricks tutorials. We focus on posting the article at Android App Development. Apart from App development tutorials, we also occasionally post other technology tips and tricks, which can be very helpful for you. Stay tuned with Techpass Master for more updates.
View All Articles

Leave a Reply

Your email address will not be published.