https://try.kotlinlang.org/#/Kotlin%20Koans/Collections/FlatMap/Task.kt个月内

它有使用flatMapmap的示例

seems both are doing the same thing, is there a sample to show the difference of using flatMap and map?

数据类型:

data class Shop(val name: String, val customers: List<Customer>)

data class Customer(val name: String, val city: City, val orders: List<Order>) {
    override fun toString() = "$name from ${city.name}"
}

data class Order(val products: List<Product>, val isDelivered: Boolean)

data class Product(val name: String, val price: Double) {
    override fun toString() = "'$name' for $price"
}

data class City(val name: String) {
    override fun toString() = name
}

the samples:

fun Shop.getCitiesCustomersAreFrom(): Set<City> =
    customers.map { it.city }.toSet()
    // would it be same with customers.flatMap { it.city }.toSet() ?

val Customer.orderedProducts: Set<Product> get() {
    return orders.flatMap { it.products }.toSet()
    // would it be same with return orders.map { it.products }.toSet()
}

推荐答案

Consider the following example: You have a simple data structure Data with a single property of type List.

class Data(val items : List<String>)

val dataObjects = listOf(
    Data(listOf("a", "b", "c")), 
    Data(listOf("1", "2", "3"))
)

flatMap vs. map

With flatMap, you can "flatten" multiple Data::items into one collection as shown with the items variable.

val items: List<String> = dataObjects
    .flatMap { it.items } //[a, b, c, 1, 2, 3]

另一方面,使用map只会生成一个列表列表.

val items2: List<List<String>> = dataObjects
    .map { it.items } //[[a, b, c], [1, 2, 3]] 

100

There's also a flatten extension on Iterable<Iterable<T>> and also Array<Array<T>> which you can use alternatively to flatMap when using those types:

val nestedCollections: List<Int> = 
    listOf(listOf(1,2,3), listOf(5,4,3))
        .flatten() //[1, 2, 3, 5, 4, 3]

Kotlin相关问答推荐

如何为集成测试配置Gradle JVM测试套件?

Android Studio中的只读集合不支持操作失败的原因是什么?

如何在Android应用判断上运行多个查询

kotlin中如何使用子类调用父静态方法?

可组合项在返回后返回时组合导航句柄

Kotlin 可空泛型

Kotlin 可空泛型

为什么记得不将 StateFlow 转换为特定类型?

异常传播如何在 CoroutineScope.async 上工作?

在 kotlin 中写入 parcer 可空值

Kotlin 中的部分类委托

kotlin 扩展属性的惰性初始化器中的这个引用

将 Completable 转换为 Single 的规范方法?

Hilt Activity 必须附加到 @AndroidEntryPoint 应用程序

Kotlin - 来自 KType 的 KClass<*>

Kotlin协程处理错误和实现

Spring Boot:更改属性占位符符号

指定为非null的参数在ArrayAdaper中为null

spring.config.location 在 Spring Boot 2.0.0 M6 上不起作用

在 Kotlin 中返回函数有不那么丑陋的方法吗?