kotlin 如何用特定键替换New map值

qcbq4gxm  于 2023-06-24  发布在  Kotlin
关注(0)|答案(2)|浏览(133)

这是原始数据。

  • 数据格式为List <Map <String,Any>>。*
#1
[
  {
    "item_id": "1234",
    "item_name": "MY ITEM 1",
    "origin_item_id": "NULL"
  },
  {
    "item_id": "9999",
    "item_name": "MY ITEM 5",
    "origin_item_id": "NULL"
  }
]

这是需要替换的新数据。

#2
[
  {
    "item_id": "1111",
    "item_name": "CHANGE ITEM 1",
    "origin_item_id": "1234"
  }
]

第一步)从#2获取origin_item_id("1234")
第二步)在#1中查找item_id为"1234"的项
第三步)替换#1的item_id:“1234”到#2(origin_item_id:"1234)数据
我应该得到以下结果。

#3
[
  {
    "item_id": "1111",
    "item_name": "CHANGE ITEM 1",
    "origin_item_id": "1234"
  }
  {
    "item_id": "9999",
    "item_name": "MY ITEM 5",
    "origin_item_id": "NULL"
  }
]

我该怎么做...

xzlaal3s

xzlaal3s1#

要做问题中所问的事情,你可以这样做

fun main() {
    val list = listOf(
        mutableMapOf(
            "item_id" to "1234",
            "item_name" to "MY ITEM 1",
            "origin_item_id" to "NULL"
        ),
        mutableMapOf(
            "item_id" to "9999",
            "item_name" to "MY ITEM 5",
            "origin_item_id" to "NULL"
        )
    )
    val changes = listOf(
        mapOf(
            "item_id" to "1111",
            "item_name" to "CHANGE ITEM 1",
            "origin_item_id" to "1234"
        ),
    )

    changes.forEach { change ->
        list.forEach {
            if (it["item_id"] == change["origin_item_id"]) {
                it["origin_item_id"] = it["item_id"]!!
                it["item_id"] = change["item_id"]!!
                it["item_name"] = change["item_name"]!!
            }
        }
    }

    println(list)
}

但是正如Sweeper所建议的那样,使用数据类而不是Map确实更好

jhdbpxl9

jhdbpxl92#

使用此解决方案,新Map将取代前一个:

val originalList = listOf(
  mapOf(
    "item_id" to "1234",
    "item_name" to "MY ITEM 1",
    "origin_item_id" to "NULL"
  ),
  mapOf(
    "item_id" to "9999",
    "item_name" to "MY ITEM 5",
    "origin_item_id" to "NULL"
  )
)

fun main() {
    val changedList = originalList.map { originalMap ->
        if( originalMap["item_id"] == "1234" )
            mapOf(
                "item_id" to "1111",
                "item_name" to "CHANGE ITEM 1",
                "origin_item_id" to "1234"
            )  
        else originalMap
        // The map function checks the maps one by one.
        // If the conditions apply, the new map will replace the original one. 
        // Otherwise (else), the original one will be returned.
    }
    println(changedList)
}

相关问题