我给出了一个整数列表。在进行进一步的开发时,我需要始终映射以下两个元素。如果输入列表包含无效的元素计数,则应删除最后一个元素。这是一个例子:

[1, 2, 3, 4, 5, 6, 7] //Input
[(1, 2), (3, 4), (5, 6)] //Output

我写了一些函数来获取所需的输出,但是我认为它们都效率不高。

首先,我尝试了一种实用的方法。但是对于结果列表,它需要两个过滤器调用和一个zip调用。因此,它遍历整个列表2.5次。

我对此提出了两个建议,尝试了一种迭代方法。它仅在列表中迭代一次,并且可能是最快的版本。但是它使用多个可变变量/列表。同样,它不像功能方法那样容易理解。 (这破坏了其余代码的简洁性)
fun main(args: Array<String>) {
    mapFunctional()
    mapIterative()
}

fun mapFunctional() {
    val list: List<Int> = listOf(1, 2, 3, 4, 5, 6, 7)

    val output: List<Pair<Int, Int>> = list.filterIndexed { index, _ ->
        index % 2 == 0
    }.zip(list.filterIndexed {
        index, _ -> index % 2 == 1
    })

    println(output)
}

fun mapIterative() {
    val list: List<Int> = listOf(1, 2, 3, 4, 5, 6, 7)

    val output: MutableList<Pair<Int, Int>> = mutableListOf()
    var index = 0
    while (index < list.size - 1) {
        output.add(list[index++] to list[index++])
    }

    println(output)
}

他们是在函数式方法中实现这一目标的好(有效)方法,还是只有经典循环才有可能?

最佳答案

如果需要List<Pair>,则可以为此使用标准库调用 windowed

val myList = listOf(1, 2, 3, 4, 5, 6, 7)
val listOfPairs = myList.windowed(2, 2).map { Pair(it[0], it[1]) }
// [(1, 2), (3, 4), (5, 6)]
windowed函数将返回List<List<Int>>,因此您必须将内部List<Int>映射到Pair<Int, Int>。默认情况下,windowed函数将删除部分窗口。

09-10 01:55
查看更多