Convert Kotlin List to Map

convert-kotlin-list-map-feature-image

In the tutorial, JavaSampleApproach will show you how to convert Kotlin List to Map.

Related posts:
Convert Kotlin Map to List

A. Convert Kotlin List to Map

Initialize data:

I. Use toMap() method

Method signature: public fun Iterable>.toMap(): Map
-> Returns a new map containing all key-value pairs from the given collection.

1. Create a read-only map

2. Create a modifiable map

II. Use associate* methods
1. associate()

Method signature: public inline fun Iterable.associate(transform: (T) -> Pair): Map

2. associateBy()
  • use public inline fun Iterable.associateBy(keySelector: (T) -> K): Map
  • use public inline fun Iterable.associateBy(keySelector: (T) -> K, valueTransform: (T) -> V): Map
  • 3. associateTo()

    Method signature: public inline fun > Iterable.associateTo(destination: M, transform: (T) -> Pair): M

    4. associateByTo()
  • use public inline fun > Iterable.associateByTo(destination: M, keySelector: (T) -> K): M
  • use public inline fun > Iterable.associateByTo(destination: M, keySelector: (T) -> K, valueTransform: (T) -> V): M
  • B. Practice

    I. Implement

    We create a Kotlin project as below:

    kotlin list to map - project structure

    1. Create data models

    – Create Address model:

    – Create Customer model:

    2. Kotlin Program

    II. Sourcecode

    KotlinConvertListToMap

    By grokonez | December 12, 2017.

    Last updated on September 12, 2018.



    Related Posts


    Got Something To Say:

    Your email address will not be published. Required fields are marked *

    *