如何在科特林的地图上迭代

发布于 2025-02-12 06:36:09 字数 715 浏览 1 评论 0 原文

因此,我是Kotlin的新手,我想知道迭代地图的标准方式是什么。我已经尝试了不同的方法,并且它们似乎都起作用,但是我不知道是否有比其余的更好,或者有一些我不知道的差异。

    var mutMap = mutableMapOf("one" to 1, "two" to 2, "tree" to 3, "four" to 4, "five" to 5)

    mutMap.forEach { entry -> println(entry) }

    mutMap.iterator().forEach { entry -> println(entry) }

    mutMap.entries.forEach { entry -> println(entry) }

    mutMap.entries.iterator().forEach { entry -> println(entry) }

    for (entry in mutMap) { println(entry) }

    for (entry in mutMap.entries) { println(entry) }

    for (entry in mutMap.iterator()) { println(entry) }

    for (entry in mutMap.entries.iterator()) { println(entry) }

另外,如果我还想在迭代时删除一个条目,那么它们都无法正常工作,对吗?

So I am new to Kotlin and I am wondering what's the standard way of iterating a Map. I have tried different ways and all of them seem to work, but I don't know if there's one better than the rest or there are some differences that I am not aware of.

    var mutMap = mutableMapOf("one" to 1, "two" to 2, "tree" to 3, "four" to 4, "five" to 5)

    mutMap.forEach { entry -> println(entry) }

    mutMap.iterator().forEach { entry -> println(entry) }

    mutMap.entries.forEach { entry -> println(entry) }

    mutMap.entries.iterator().forEach { entry -> println(entry) }

    for (entry in mutMap) { println(entry) }

    for (entry in mutMap.entries) { println(entry) }

    for (entry in mutMap.iterator()) { println(entry) }

    for (entry in mutMap.entries.iterator()) { println(entry) }

Also, if I wanted to also delete an entry while iterating over them, none of them would work, right?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

情感失落者 2025-02-19 06:36:12

您可以使用迭代器的remove()函数来删除地图项目。

fun main() {
    val map = mutableMapOf("user1" to 29, "user2" to 25, "user3" to 26)
    val iterator = map.entries.iterator()
    println("Before iteration: $map")
    while (iterator.hasNext()) {
        val (key, value) = iterator.next()
        if (key == "user1") {
            iterator.remove()
        }

    }
    println("After iteration: $map")
}

它将打印:

Before iteration: {user1=29, user2=25, user3=26}
After iteration: {user2=25, user3=26}

You can use the remove() function of the iterator to remove the item of map.

fun main() {
    val map = mutableMapOf("user1" to 29, "user2" to 25, "user3" to 26)
    val iterator = map.entries.iterator()
    println("Before iteration: $map")
    while (iterator.hasNext()) {
        val (key, value) = iterator.next()
        if (key == "user1") {
            iterator.remove()
        }

    }
    println("After iteration: $map")
}

It'll prints:

Before iteration: {user1=29, user2=25, user3=26}
After iteration: {user2=25, user3=26}
当梦初醒 2025-02-19 06:36:11

如果您浏览kotlin的 collections 包装包装有很多whoooole poxpare您可以使用的东西,是的!许多不同的功能使您可以深入研究特定的数据(例如键或值与条目,或提供索引)或在处理集合时获得特定的行为。

您给出的示例基本上都是同一回事。 函数在各种类型的集合上:

inline fun <T> Array<out T>.forEach(action: (T) -> Unit)
(source)

// a bunch of other Kotlin-specific Array types

inline fun <T> Iterable<T>.forEach(action: (T) -> Unit)
inline fun <K, V> Map<out K, V>.forEach(
    action: (Entry<K, V>) -> Unit)
inline fun <T> Iterator<T>.forEach(operation: (T) -> Unit)

这是这些集合的源代码(每个函数下都有一个源链接 很有用!

public inline fun <T> Iterable<T>.forEach(action: (T) -> Unit): Unit {
    for (element in this) action(element)
}

public inline fun <K, V> Map<out K, V>.forEach(action: (Map.Entry<K, V>) -> Unit): Unit {
    for (element in this) action(element)
}

public inline fun <T> Iterator<T>.forEach(operation: (T) -> Unit): Unit {
    for (element in this) operation(element)
}

主页, rel =“ nofollow noreferrer”> basic for 循环,正如文档所说迭代。您的示例基本上与正在发生的事情相同,只是在 foreach -&gt中的各个点跳入;循环基础 - &gt;获取迭代器进程。

唯一不同的部分是当您调用条目时,返回 set 保留键/值 entry 配对 - 因此您正在迭代那,而不是地图本身。但是,等等,如果您在 MAP 上调用 iterator(),会发生什么

public inline operator fun <K, V> Map<out K, V>.iterator(): Iterator<Map.Entry<K, V>> = entries.iterator()

它使用条目本身!所以,是的,他们都是一样的


,我认为这取决于这

  • 不需呼叫 hasnext()在其上或任何
  • 适合Kotlin的声明样式,可以链接,并自动通过变量传递,而不是您必须声明它们
  • 有时是基本的 循环对于您正在做的事情更可读,尤其是在修改某种结果 actibal时(这与 fold <更可比) /代码> foreach ,但无论如何
  • 条目 map 意味着您在链条链时要明确有关正在使用的内容 foreach 上您如何指定或值仅与这些范围 for each 相同,但它更清楚

If you browse through Kotlin's Collections package there is a whoooole lot of stuff you can use, yeah! Lots of different functions that let you drill down into specific pieces of data (like keys or values vs entries, or providing indices) or getting specific behaviour as you process a collection.

The examples you've given are all basically the same thing though. Here's the page for all the forEach functions on the various types of collections:

inline fun <T> Array<out T>.forEach(action: (T) -> Unit)
(source)

// a bunch of other Kotlin-specific Array types

inline fun <T> Iterable<T>.forEach(action: (T) -> Unit)
inline fun <K, V> Map<out K, V>.forEach(
    action: (Entry<K, V>) -> Unit)
inline fun <T> Iterator<T>.forEach(operation: (T) -> Unit)

And here's the source code for those (there's a source link under every function's main page, useful to know about! You can see exactly how they work)

public inline fun <T> Iterable<T>.forEach(action: (T) -> Unit): Unit {
    for (element in this) action(element)
}

public inline fun <K, V> Map<out K, V>.forEach(action: (Map.Entry<K, V>) -> Unit): Unit {
    for (element in this) action(element)
}

public inline fun <T> Iterator<T>.forEach(operation: (T) -> Unit): Unit {
    for (element in this) operation(element)
}

So really they're all wrappers for a basic for loop, which as the documentation says, iterates through anything that provides an iterator. Your examples are all basically the same thing that's happening, just jumping in at various points in the forEach -> basic for loop -> get an iterator process.

The only part that's different is when you call entries, which returns a Set holding the key/value Entry pairs - so you're iterating over that, rather than the Map itself. But wait, what does happen if you call iterator() on a Map?

public inline operator fun <K, V> Map<out K, V>.iterator(): Iterator<Map.Entry<K, V>> = entries.iterator()

It uses entries itself! So yeah they're all the same thing


Really I think it comes down to this

  • no need to call iterator() on anything unless you know you need one for some reason, like you're going to be calling hasNext() on it or whatever
  • forEach fits with Kotlin's more declarative style, can be chained, and automatically passes in variables instead of you having to declare them
  • sometimes a basic for loop is more readable for what you're doing though, especially if you're modifying some kind of result variable (which is more comparable to a fold than a forEach but anyway
  • accessing entries on a Map means you're being explicit about what you're working with when you chain a forEach onto it, similar to how you can specify keys or values and only work with those. It's the same as just calling forEach on the map itself, but it's clearer
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文