我有两个mutableLists,listOfA有很多对象,包括重复项,而listOfB有更少的对象。因此,我想使用listOfB来过滤listOfA中的相似对象,以便所有列表在末尾具有相等数量的具有相等键的对象。下面的代码可以解释更多。
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
*/
}
答案 0 :(得分:1)
如果您想直接在该distinctListOfA
上进行操作,则可以使用removeAll
从其中删除所有匹配的条目。只需确保只对B
的键进行一次初始化,以免每次应用谓词时都不会对其进行求值:
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
进行操作可能更有意义),那么可能是您所追求的: / p>
val map : MutableMap<String, ObjA> = ...
map.keys.retainAll(listOfB.map { it.key })
retainAll
仅保留那些与给定集合条目匹配的值,并且在应用它之后,映射现在仅包含键one
和two
。
如果您想保留以前的列表/地图,而想要一个新的列表/地图,则可以在对其进行操作之前先调用以下内容:
val newList = distinctListOfA.toList() // creates a new list with the same entries
val newMap = yourPreviousMap.toMutableMap() // create a new map with the same entries