map flatmap

1.map

public inline fun  Iterable.map(transform: (T) -> R): List {
    return mapTo(ArrayList(collectionSizeOrDefault(10)), transform)
}

public inline fun > Iterable.mapTo(destination: C, transform: (T) -> R): C {
    for (item in this)
        destination.add(transform(item))
    return destination
}

2.flatmap

public inline fun  Iterable.flatMap(transform: (T) -> Iterable): List {
    return flatMapTo(ArrayList(), transform)
}

public inline fun > Iterable.flatMapTo(destination: C, transform: (T) -> Iterable): C {
    for (element in this) {
        val list = transform(element)
        destination.addAll(list)
    }
    return destination
}

测试用例

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

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

data class Order(val products: List, 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.getCity(): List {

    return customers.map { it.city }
}

fun Shop.getProduct(): List {
    return customers.flatMap { it ->
        it.orders.flatMap { it.products }
    }
}

    @Test
    fun testFor() {

        val shop = Shop(
            "红旗超市", listOf(
                Customer(
                    "张三", City("北京"), listOf(
                        Order(
                            listOf(
                                Product("芹菜", 10.0),
                                Product("白菜", 1.5)
                            ), false
                        ),
                        Order(
                            listOf(
                                Product("白酒", 1.2),
                                Product("啤酒", 0.3)
                            ), false
                        )
                    )
                ), Customer(
                    "李四", City("广州"), listOf(
                        Order(
                            listOf(
                                Product("苹果", 10.0),
                                Product("梨子", 1.5)
                            ), false
                        ),
                        Order(
                            listOf(
                                Product("咖啡", 10.0),
                                Product("可乐", 1.5)
                            ), false
                        )
                    )
                )
            )
        )

        val cityList = shop.getCity()
        for (c in cityList) {
            Log.i(TAG, "city: $c")
        }

        //
        val productList = shop.getProduct()
        for (p in productList) {
            Log.i(TAG, "product: $p")
        }
    }

运行结果


image.png

你可能感兴趣的:(map flatmap)