本文介绍了Kotlin中FlatMap与Map的用例是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

它具有使用flatMapmap

似乎两者都在做同一件事,是否有示例显示使用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
}

样本:

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()
}

推荐答案

请考虑以下示例:您有一个简单的数据结构Data,其单个属性的类型为List.

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"))
)

flatMapmap

flatMap vs. map

使用flatMap,您可以将多个Data::items展平"到一个集合中,如items变量所示.

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只会产生一个列表列表.

Using map, on the other hand, simply results in a list of lists.

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

flatten

flatten

Iterable<Iterable<T>>Array<Array<T>>上还有一个flatten扩展名,使用这些类型时,您可以将其替换为flatMap:

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中FlatMap与Map的用例是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-14 08:29