简体   繁体   English

将两个不同的数据类列表合并到第三个 Kotlin

[英]Merge two different data class lists in to the the third one Kotlin

I want to add additional field to my new data class from the old one which has an extra field of balance value.我想从具有额外余额值字段的旧数据类中向我的新数据类添加额外字段。 I have created data class list with the ID and the Values (balance), which I want to merge first data class list with the second to make 3rd list - similarly like union in sql.我已经创建了带有 ID 和值(余额)的数据类列表,我想将第一个数据类列表与第二个数据类列表合并以制作第三个列表 - 类似于 sql 中的联合。

first data class第一个数据类

data class Coin(
  val id: String,
  val price_usd: Double,
  val name: String,
  val rank: Int,
  val symbol: String
)

second data class第二类数据

 data class CurrencyBalance(
     val id: String,
     val quantity: String
 )

The aim is to create this type of data class list目的是创建这种类型的数据类列表

data class CoinData(
  val id: String,
  val price_usd: Double,
  val name: String,
  val rank: Int,
  val symbol: String,
  val quantity: String
)

Is something like this what you are looking for?你正在寻找这样的东西吗?

fun convert(currencyBalances: List<CurrencyBalance>, coins: List<Coin>): List<CoinData> =
    currencyBalances.map { currencyBalance ->
        coins.firstOrNull { coin -> coin.id == currencyBalance.id }
            ?.let { coin -> CoinData(coin.id, coin.price_usd, coin.name, coin.rank, coin.symbol, currencyBalance.value) }
    }.filterNotNull()

I assumed here that the fields in a CurrencyBalance are called id and value我在这里假设CurrencyBalance中的字段称为idvalue

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Kotlin:将两个不同的列表合并为一个,并从两个列表中选择数据 - Kotlin: Merge two different list into one with selected data from both lists Kotlin:将三个列表合并为一个,并从三个列表中选择数据 - Kotlin: Merge three lists into one with selected data from three lists 合并两个不同对象的列表 - merge two lists of different objects 如何在kotlin中组合两个不同长度的列表? - How to combine two different length lists in kotlin? 如何从两个不同的 db.collections 中获取数据并将它们合并到 Kotlin-Firebase 中的一个类中? - How can I take data from two different db.collections and unite them under one class in Kotlin-Firebase? 比较和替换Kotlin中大小不同的两个列表中的项目? - Comparing and replacing items in two lists with different sizes in Kotlin? 我可以在Kotlin中将两个条件合并为一行吗? - Can I always merge two conditions into one row in Kotlin? 如何在 Android Manifest 中声明两个不同的应用程序或将它们合并为一个应用程序类 - How to declare two different application in Android Manifest or merge them into one application class Kotlin - 使用startsWith()比较两个列表 - Kotlin - Compare two lists with startsWith() 可观察列表在Kotlin中合并为单个可观察列表 - Observable Lists merge to a single observable List in Kotlin
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM