DEV Community

loizenai
loizenai

Posted on

Kotlin Map collection with flatMap(), flatMapTo() methods

Kotlin Map collection with flatMap(), flatMapTo() methods

https://grokonez.com/kotlin/kotlin-map-collection-flatmap-flatmapto-methods

In the tutorial, JavaSampleApproach will show you how to work with Kotlin Map flatMap() and flatMapTo() methods.

I. Kotlin Map collection with flatMap(), flatMapTo()

1. with flatMap() method

We use flatMap() to create a single list of all entries from results of [transform] function being invoked on each entry of original map.

Method signature:


public inline fun  Map.flatMap(transform: (Map.Entry) -> Iterable): List

Practice:


val customerMap = mapOf(Pair(Customer("Jack", 25), Address("NANTERRE CT", "77471")),
                        Pair(Customer("Mary", 37), Address("W NORMA ST", "77009")),
                        Pair(Customer("Peter", 18), Address("S NUGENT AVE", "77571")),
                        Pair(Customer("Amos", 23), Address("E NAVAHO TRL", "77449")),
                        Pair(Customer("Craig", 45), Address("AVE N", "77587")))

val customerList = customerMap.flatMap { (customer, _) -> listOf(customer) }
customerList.forEach{ println(it) }
/*
    Customer(name=Jack, age=25)
    Customer(name=Mary, age=37)
    Customer(name=Peter, age=18)
    Customer(name=Amos, age=23)
    Customer(name=Craig, age=45)
*/

val addressList = customerMap.flatMap { (_, address) -> listOf(address) }
addressList.forEach{ println(it) }
/*
    Address(street=NANTERRE CT, postcode=77471)
    Address(street=W NORMA ST, postcode=77009)
    Address(street=S NUGENT AVE, postcode=77571)
    Address(street=E NAVAHO TRL, postcode=77449)
    Address(street=AVE N, postcode=77587)
*/

val customerInfos = customerMap.flatMap { (customer, address) -> listOf("${customer.name} lives at ${address.street}") }
customerInfos.forEach{ println(it) }
/*
    Jack lives at NANTERRE CT
    Mary lives at W NORMA ST
    Peter lives at S NUGENT AVE
    Amos lives at E NAVAHO TRL
    Craig lives at AVE N
*/

More at:

Kotlin Map collection with flatMap(), flatMapTo() methods

https://grokonez.com/kotlin/kotlin-map-collection-flatmap-flatmapto-methods

Top comments (0)