在 Kotlin 中,如何在迭代时修改列表的内容 [英] In Kotlin, how do you modify the contents of a list while iterating

查看:78
本文介绍了在 Kotlin 中,如何在迭代时修改列表的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个清单:

val someList = listOf(1, 20, 10, 55, 30, 22, 11, 0, 99)

我想在修改一些值的同时对其进行迭代.我知道我可以使用 map 做到这一点,但这会复制列表.

And I want to iterate it while modifying some of the values. I know I can do it with map but that makes a copy of the list.

val copyOfList = someList.map { if (it <= 20) it + 20 else it }

没有副本我该怎么做?

注意: 这个问题是作者有意编写和回答的(Self-Answered Questions),以便在 SO 中出现对 Kotlin 常见问题的惯用答案.还要澄清一些为 Kotlin alpha 编写的非常古老的答案,这些答案对于当前的 Kotlin 并不准确.

Note: this question is intentionally written and answered by the author (Self-Answered Questions), so that the idiomatic answers to commonly asked Kotlin topics are present in SO. Also to clarify some really old answers written for alphas of Kotlin that are not accurate for current-day Kotlin.

推荐答案

首先,并非所有的列表复制都是不好的.有时副本可以利用 CPU 缓存并且速度非常快,这取决于列表、大小和其他因素.

First, not all copying of a list is bad. Sometimes a copy can take advantage of CPU cache and be extremely fast, it depends on the list, size, and other factors.

其次,要就地"修改列表,您需要使用可变的列表类型.在您的示例中,您使用返回 List<T> 接口的 listOf 接口,这是只读的.您需要直接引用可变列表的类(即ArrayList),或者使用辅助函数arrayListOflinkedListOf是惯用的Kotlin创建一个 MutableList<T> 引用.一旦你有了它,你可以使用 listIterator() 迭代列表,它有一个变异方法 set().

Second, for modifying a list "in-place" you need to use a type of list that is mutable. In your sample you use listOf which returns the List<T> interface, and that is read-only. You need to directly reference the class of a mutable list (i.e. ArrayList), or it is idiomatic Kotlin to use the helper functions arrayListOf or linkedListOf to create a MutableList<T> reference. Once you have that, you can iterate the list using the listIterator() which has a mutation method set().

// create a mutable list
val someList = arrayListOf(1, 20, 10, 55, 30, 22, 11, 0, 99)

// iterate it using a mutable iterator and modify values 
val iterate = someList.listIterator()
while (iterate.hasNext()) {
    val oldValue = iterate.next()
    if (oldValue <= 20) iterate.set(oldValue + 20)
}

这将在迭代发生时更改列表中的值,并且对所有列表类型都有效.为了使这更容易,请创建可以重复使用的有用的扩展函数(见下文).

This will change the values in the list as iteration occurs and is efficient for all list types. To make this easier, create helpful extension functions that you can re-use (see below).

您可以为 Kotlin 编写扩展函数,为任何 MutableList 实现进行就地可变迭代.这些内联函数的执行速度与迭代器的任何自定义使用一样快,并且内联以提高性能.非常适合 Android 或任何地方.

You can write extension functions for Kotlin that do an in place mutable iteration for any MutableList implementation. These inline functions will perform as fast as any custom use of the iterator and is inlined for performance. Perfect for Android or anywhere.

这是一个 mapInPlace 扩展函数(它保留了这些类型函数的典型命名,例如 mapmapTo):

Here is a mapInPlace extension function (which keeps the naming typical for these type of functions such as map and mapTo):

inline fun <T> MutableList<T>.mapInPlace(mutator: (T)->T) {
    val iterate = this.listIterator()
    while (iterate.hasNext()) {
        val oldValue = iterate.next()
        val newValue = mutator(oldValue)
        if (newValue !== oldValue) {
            iterate.set(newValue)
        }
    }
}

示例调用此扩展函数的任何变体:

Example calling any variation of this extension function:

val someList = arrayListOf(1, 20, 10, 55, 30, 22, 11, 0, 99)
someList.mapInPlace { if (it <= 20) it + 20 else it }

这并不适用于所有Collection,因为大多数迭代器只有一个remove()方法,没有set().

This is not generalized for all Collection<T>, because most iterators only have a remove() method, not set().

您可以使用类似的方法处理泛型数组:

You can handle generic arrays with a similar method:

inline fun <T> Array<T>.mapInPlace(mutator: (T)->T) {
    this.forEachIndexed { idx, value ->
        mutator(value).let { newValue ->
            if (newValue !== value) this[idx] = mutator(value)
        }
    }
}

对于每个原始数组,使用以下变体:

And for each of the primitive arrays, use a variation of:

inline fun BooleanArray.mapInPlace(mutator: (Boolean)->Boolean) {
    this.forEachIndexed { idx, value ->
        mutator(value).let { newValue ->
            if (newValue !== value) this[idx] = mutator(value)
        }
    }
}

关于仅使用引用相等的优化

上面的扩展函数优化了一点,如果它没有更改为不同的实例,则不设置值,检查使用 ===!==参照平等.不值得检查 equals()hashCode() 因为调用它们有一个未知的成本,并且实际上引用相等捕获任何更改值的意图.

About the Optimization using only Reference Equality

The extension functions above optimize a little by not setting the value if it has not changed to a different instance, checking that using === or !== is Referential Equality. It isn't worth checking equals() or hashCode() because calling those has an unknown cost, and really the referential equality catches any intent to change the value.

这里是显示函数工作的单元测试用例,以及与制作副本的 stdlib 函数 map() 的小比较:

Here are unit test cases showing the functions working, and also a small comparison to the stdlib function map() that makes a copy:

class MapInPlaceTests {
    @Test fun testMutationIterationOfList() {
        val unhappy = setOf("Sad", "Angry")
        val startingList = listOf("Happy", "Sad", "Angry", "Love")
        val expectedResults = listOf("Happy", "Love", "Love", "Love")

        // modify existing list with custom extension function
        val mutableList = startingList.toArrayList()
        mutableList.mapInPlace { if (it in unhappy) "Love" else it }
        assertEquals(expectedResults, mutableList)
    }

    @Test fun testMutationIterationOfArrays() {
        val otherArray = arrayOf(true, false, false, false, true)
        otherArray.mapInPlace { true }
        assertEquals(arrayOf(true, true, true, true, true).toList(), otherArray.toList())
    }

    @Test fun testMutationIterationOfPrimitiveArrays() {
        val primArray = booleanArrayOf(true, false, false, false, true)
        primArray.mapInPlace { true }
        assertEquals(booleanArrayOf(true, true, true, true, true).toList(), primArray.toList())
    }

    @Test fun testMutationIterationOfListWithPrimitives() {
        val otherList = arrayListOf(true, false, false, false, true)
        otherList.mapInPlace { true }
        assertEquals(listOf(true, true, true, true, true), otherList)
    }
}

这篇关于在 Kotlin 中,如何在迭代时修改列表的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆