从列表中删除不在另一个列表中的元素-Kotlin [英] Removing elements from a list which are not in another list - Kotlin
问题描述
我有两个mutableLists,listOfA有很多对象,包括重复项,而listOfB有更少的对象.因此,我想使用listOfB来过滤listOfA中的相似对象,以便所有列表在末尾具有相等数量的具有相等键的对象.下面的代码可以解释更多.
I have two mutableLists, listOfA has so many objects including duplicates while listOfB has fewer. So I want to use listOfB to filter similar objects in listOfA so all list will have equal number of objects with equivalent keys at the end. Code below could explain more.
fun main() {
test()
}
data class ObjA(val key: String, val value: String)
data class ObjB(val key: String, val value: String, val ref: Int)
fun test() {
val listOfA = mutableListOf(
ObjA("one", ""),
ObjA("one", "o"),
ObjA("one", "on"),
ObjA("one", "one"),
ObjA("two", ""),
ObjA("two", "2"),
ObjA("two", "two"),
ObjA("three", "3"),
ObjA("four", "4"),
ObjA("five", "five")
)
//Use this list's object keys to get object with similar keys in above array.
val listOfB = mutableListOf(
ObjB("one", "i", 2),
ObjB("two", "ii", 5)
)
val distinctListOfA = listOfA.distinctBy { it.key } //Remove duplicates in listOfA
/*
val desiredList = doSomething to compare keys in distinctListOfA and listOfB
for (o in desiredList) {
println("key: ${o.key}, value: ${o.value}")
}
*/
/* I was hoping to get this kind of output with duplicates removed and comparison made.
key: one, value: one
key: two, value: two
*/
}
推荐答案
如果您想直接在distinctListOfA
上进行操作,则可以使用
If you want to operate directly on that distinctListOfA
you may want to use removeAll
to remove all the matching entries from it. Just be sure that you initialize the keys of B
only once so that it doesn't get evaluated every time the predicate is applied:
val keysOfB = listOfB.map { it.key } // or listOfB.map { it.key }.also { keysOfB ->
distinctListOfA.removeAll {
it.key !in keysOfB
}
//} // if "also" was used you need it
如果在评估了唯一值之后已有一个MutableMap<String, ObjA>
(并且我认为在此处对Map
进行操作可能更有意义),则可能是您所追求的:
If you have a MutableMap<String, ObjA>
in place after evaluating your unique values (and I think it may make more sense to operate on a Map
here), the following might be what you are after:
val map : MutableMap<String, ObjA> = ...
map.keys.retainAll(listOfB.map { it.key })
如果您想保留以前的列表/地图,而想要一个新的列表/地图,则可以在对其进行操作之前先调用以下内容:
In case you want to keep your previous lists/maps and rather want a new list/map instead, you may just call something like the following before operating on it:
val newList = distinctListOfA.toList() // creates a new list with the same entries
val newMap = yourPreviousMap.toMutableMap() // create a new map with the same entries
这篇关于从列表中删除不在另一个列表中的元素-Kotlin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!