kotlin 集合 map flatten flatMap

本文深入解析了Kotlin中集合操作map, flatten和flatMap的使用方法和区别。map用于将集合中的元素转换为另一种类型并生成新集合;flatten用于将嵌套的集合扁平化为单一集合;flatMap结合了map和flatten的功能,先转换再扁平化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

map

map就是将transform方法产生的结果添加到一个新的集合里面去,然后返回这个新的集合

/**
 * Returns a list containing the results of applying the given [transform] function
 * to each element in the original collection.
 * 
 * @sample samples.collections.Collections.Transformations.map
 */
public inline fun <T, R> Iterable<T>.map(transform: (T) -> R): List<R> {
    return mapTo(ArrayList<R>(collectionSizeOrDefault(10)), transform)
}

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

flatten

flatten 处理嵌套集合,遍历这个嵌套集合,将每一个子集合中的元素通过addAll方法添加到新的集合中,最终得到一个扁平化的集合

/**
 * Returns a single list of all elements from all collections in the given collection.
 * @sample samples.collections.Iterables.Operations.flattenIterable
 */
public fun <T> Iterable<Iterable<T>>.flatten(): List<T> {
    val result = ArrayList<T>()
    for (element in this) {
        result.addAll(element)
    }
    return result
}

flatMap

flatMap 遍历集合中的元素,然后将每个元素传入transform中处理后得到一个列表,将这个列表的所有元素添加到destination中,最终得到一个扁平化的列表

/**
 * Returns a single list of all elements yielded from results of [transform] function being invoked on each element of original collection.
 */
public inline fun <T, R> Iterable<T>.flatMap(transform: (T) -> Iterable<R>): List<R> {
    return flatMapTo(ArrayList<R>(), transform)
}

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

可见,flatMap其实可以看作由flatten和map进行组合之后的方法,组合方式根据具体情况来定。
仅仅是对一个集合进行扁平化操作时,使用flatten就可以了。
如果需要对其中的元素进行一些“加工”,可以考虑使用flatMap

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值