从列表中删除不在另一个列表中的元素 - Kotlin

Nux*_*Nux 3 kotlin

我有两个可变列表,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
     */
}
Run Code Online (Sandbox Code Playgroud)

Rol*_*and 8

如果您想直接对其进行操作,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
Run Code Online (Sandbox Code Playgroud)

如果您MutableMap<String, ObjA>在评估了您的独特价值后有一个到位(我认为在Map这里操作可能更有意义),以下可能是您所追求的:

val map : MutableMap<String, ObjA> = ...
map.keys.retainAll(listOfB.map { it.key })
Run Code Online (Sandbox Code Playgroud)

retainAll只保留那些与给定集合条目匹配的值,在应用它之后,映射现在只包含键onetwo

如果您想保留以前的列表/地图,而想要一个新的列表/地图,您可以在对其进行操作之前调用以下内容:

val newList = distinctListOfA.toList() // creates a new list with the same entries
val newMap = yourPreviousMap.toMutableMap() // create a new map with the same entries
Run Code Online (Sandbox Code Playgroud)