更新所有列表元素基于函数结果

huangapple go评论54阅读模式
英文:

Update all list element based on the function result

问题

以下是您要求的翻译部分:

有很多在互联网和stackoverflow上的示例但据我所见它是根据索引实现的但我想要根据单个函数的结果来更新所有项目

下面的示例是我的简化版本

data class Person(val id: Int, val name: String)

var tempList: List<Pair<Person, Boolean?>> = emptyList()

val personList = listOf(Person(1, "1"), Person(2, "2"), Person(3, "3"))

fun processPerson(person: Person): Boolean {
    return person.name == "1"
}

fun main() {
    tempList = personList.map { item ->
        Pair(item, null)
    }
    
    tempList.forEach { item ->
        println(processPerson(item.first))
    }
}

我希望这可以满足您的要求。

英文:

There are loads of examples on the internet and on stackoverflow. But as far as I can see it is implemented according to index. But I want all items to be updated based on a single function result.

Below example is my simpyfied version:

data class Person(val id: Int, val name: String)

var tempList: List&lt;Pair&lt;Person, Boolean?&gt;&gt; = emptyList()


val personList = listOf(Person(1, &quot;1&quot;), Person(2, &quot;2&quot;), Person(3, &quot;3&quot;))

fun processPerson(person: Person): Boolean {    
    return person.name == &quot;1&quot;
}

fun main() {
    tempList = personList.map { item -&gt;
        Pair(item, null)
    }
    
    tempList.forEach { item -&gt;
        println(processPerson(item.first))
    }
}

Expected updated version of my list is:

listOf(Pair(Person(1, &quot;1&quot;), true), Pair(Person(2, &quot;2&quot;), false), Pair(Person(3, &quot;3&quot;), false))

答案1

得分: 2

以下是您要翻译的内容:

您可以立即构建列表如下:

tempList = personList.map { item ->
    Pair(item, processPerson(item))
}

如果您真的需要使用初始的 tempList,那么您唯一能做的是:

tempList = tempList.map { 
    Pair(it.first, processPerson(it.first))
}

或者

tempList = tempList.map {
    it.copy(second = processPerson(it.first))
}

由于原始的 Pair 值是不可变的,所以无法更新它们,唯一的选择是映射到新的 Pair。

英文:

You could have constructed the list right away with

tempList = personList.map { item -&gt;
    Pair(item, processPerson(item))
}

If you really need to work with the initial tempList then all you can do is

tempList = tempList.map { 
    Pair(it.first, processPerson(it.first))
}

or

tempList = tempList.map {
    it.copy(second = processPerson(it.first))
}

There's no way to update the original Pairs because their values are immutable so the only option is to map to new Pairs

huangapple
  • 本文由 发表于 2023年5月17日 19:45:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76271750.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定