Home » JVM Languages » Kotlin » Kotlin – Convert List to Map Examples

About Venkatesh Nukala

Venkatesh Nukala
Venkatesh Nukala is a Software Engineer working for Online Payments Industry Leading company. In my free time, I would love to spend time with family and write articles on technical blogs. More on JavaProgramTo.com

Kotlin – Convert List to Map Examples

1. Overview In this tutorial, We’ll learn how to convert the List to Map in Kotlin programming. Let us explore the different ways to do it.

1. Overview

In this tutorial, We’ll learn
how to convert the List to Map in Kotlin programming. Let us explore the different ways to do this conversion.

Kotlin provides a set of methods for the functionality.

  • associate()
  • associateBy()
  • map() and toMap()
  • Running for loop and set to map

First created a Website class with site name and its rank value. Next, Created and added 4 objects to list.

Converting the List to Map is shown in the below sections with example programs.

2. Kotlin List to Map with associate() method

Use associate() method to convert the List of object to Map with the needed type for key, value pairs.

Pass the Pair() object with the key, value pair object and internally it iterates over the loop.

package com.javaprogramto.kotlin.collections.list.map

data class Website(var site: String, var rank: Long);

fun main(args: Array<String>) {

    var websiteranks: List<Website> = listOf(
        Website("google.com", 1),
        Website("youtube.com", 2),
        Website("amazon.com", 3),
        Website("yahoo.com", 4)
    );

    println("List values : $websiteranks")

    val finalMap : Map<String, Long> = websiteranks.associate { Pair(it.site, it.rank) };

    println("Final map from list using associate : $finalMap")

    val mapValueCustomType : Map<String, Website> = websiteranks.associate { Pair(it.site, it) };
    println("Map value as custom type using associate : $mapValueCustomType")

}

Output:

List values : [Website(site=google.com, rank=1), Website(site=youtube.com, rank=2), Website(site=amazon.com, rank=3), Website(site=yahoo.com, rank=4)]
Final map from list using associate : {google.com=1, youtube.com=2, amazon.com=3, yahoo.com=4}
Map value as custom type using associate : {google.com=Website(site=google.com, rank=1), youtube.com=Website(site=youtube.com, rank=2), amazon.com=Website(site=amazon.com, rank=3), yahoo.com=Website(site=yahoo.com, rank=4)}

3. Kotlin List to Map with associateBy() method

Next, use the associateBy() method to convert list to map in another way.

package com.javaprogramto.kotlin.collections.list.map

fun main(args: Array<String>){
    var websiteranks: List<Website> = listOf(
        Website("google.com", 1),
        Website("youtube.com", 2),
        Website("amazon.com", 3),
        Website("yahoo.com", 4)
    );

    val finalMap : Map<String, Long> = websiteranks.associateBy({it.site}, {it.rank});

    println("Final map from list using associateBy: $finalMap")

    val mapValueCustomType : Map<String, Website> = websiteranks.associateBy({it.site}, {it})
    println("Map value as custom type using associateBy : $mapValueCustomType")

}

Output:

Final map from list using associateBy: {google.com=1, youtube.com=2, amazon.com=3, yahoo.com=4}
Map value as custom type using associateBy : {google.com=Website(site=google.com, rank=1), youtube.com=Website(site=youtube.com, rank=2), amazon.com=Website(site=amazon.com, rank=3), yahoo.com=Website(site=yahoo.com, rank=4)}

4. Kotlin List to Map with map() and toMap() methods

Next, use map() and toMap() methods on the list object.

map() method returns ArrayList.

toMap() method returns Map object.

package com.javaprogramto.kotlin.collections.list.map

// kotlin program to convert list to map using map() and toMap() methods.
fun main(args: Array<String>){
    var websiteranks: List<Website> = listOf(
        Website("google.com", 1),
        Website("youtube.com", 2),
        Website("amazon.com", 3),
        Website("yahoo.com", 4)
    );

    val finalMap : Map<Long, String> = websiteranks.map { it.rank to it.site }.toMap()

    println("Final map from list using map() and toMap() methods : $finalMap")

    val mapValueCustomType : Map<String, Website> = websiteranks.map{it.site to it}.toMap();
    println("Map value as custom type using map() and toMap() methods : $mapValueCustomType")

}

Output:

Final map from list using map() and toMap() methods : {1=google.com, 2=youtube.com, 3=amazon.com, 4=yahoo.com}
Map value as custom type using map() and toMap() methods : {google.com=Website(site=google.com, rank=1), youtube.com=Website(site=youtube.com, rank=2), amazon.com=Website(site=amazon.com, rank=3), yahoo.com=Website(site=yahoo.com, rank=4)}

5. Kotlin List to Map Using Loops

Finally, Look at the conversion to Map using for loops with normal iteration. In this way, we get the each value from list and set to a new map.

// kotlin program to convert list to map using for each loop
fun main(args: Array<String>) {
    var websiteranks: List<Website> = listOf(
        Website("google.com", 1),
        Website("youtube.com", 2),
        Website("amazon.com", 3),
        Website("yahoo.com", 4)
    );

    val finalMap: MutableMap<String, Long> = HashMap();

    for (website in websiteranks) {
        finalMap[website.site] = website.rank;
    }

    println("Map from list using custom iterating the list with for loop : $finalMap")

}

Output:

Map from list using custom iterating the list with for loop : {google.com=1, amazon.com=3, yahoo.com=4, youtube.com=2}

6. Conclusion

In this article, we have seen the
different ways to do conversion from List to Map.

Among all methods, associate() method is the right choice and mostly used in the real time applications.

Next, use toMap() method if you are iterating the list and doing some other operations.

But, toMap() method is more readable.

GitHub

Kotlin List to Array

Published on Java Code Geeks with permission by Venkatesh Nukala, partner at our JCG program. See the original article here: Kotlin – Convert List to Map Examples

Opinions expressed by Java Code Geeks contributors are their own.

(0 rating, 0 votes)
You need to be a registered member to rate this.
Start the discussion Views Tweet it!
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments