Kotlin 代码 - FlatMap 在这里如何工作?

Kotlin code - how does FlatMap work here?

以下是 LeetCode 解决方案中的代码。

这是描述:

Given an array A of non-negative integers, half of the integers in A are odd, and half of the integers are even.

Sort the array so that whenever A[i] is odd, i is odd; and whenever A[i] is even, i is even.

我设法编写了有效的代码,但我的代码几乎像 Java 但在 Kotlin 中(一个常见问题 - 我知道)。

我在评论中找到这段代码:

   fun sortArrayByParityII(A: IntArray): IntArray {
        val even = A.filter { it % 2 == 0 }
        val odd = A.filter { it % 2 == 1 }
        return even.zip(odd).flatMap { listOf(it.first, it.second) }.toIntArray()
    }

我知道前几行是这样的。他们简单地将数组过滤成偶数和奇数数组。 我什至明白(在查找之后)"zip" 的作用。

我不明白这是做什么的:

flatMap { listOf(it.first, it.second) }

让我们一步步来看:

fun main() {
    val list = (1..10).toList()
    val even = list.filter { it % 2 == 0 } // [2, 4, 6, 8, 10]
    val odd = list.filter { it % 2 == 1 } // [1, 3, 5, 7, 9]
    val zipped = even.zip(odd) // [(2, 1), (4, 3), (6, 5), (8, 7), (10, 9)]
    val flatten = zipped.flatMap { listOf(it.first, it.second) } // [2, 1, 4, 3, 6, 5, 8, 7, 10, 9]
}

flatMap 接受一个 returns 列表的函数,并将该列表的元素插入到初始列表中。所以 [(2, 1), (4, 3)] 变成 [2, 1, 4, 3]

给定筛选列表:

odd = [1,3,5,7,9,...]
even = [2,4,6,8,...] 

zip 函数将每个列表的每个单项连接成一个元组列表:

even.zip(odd)
// [(2,1),(4,3),(6,5),(8,7),...]

此处的平面地图正在对每个项目(元组)和returns单个列表进行操作,它首先选择每个元组中的第二个项目并将它们添加到单个列表中:

even.zip(add).flatMap { listOf(it.first, it.second) }
// [2, 1, 4, 3, 6, 5, 8, 7, 10, 9]