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.
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
private val coinBalance: List<CurrencyBalance> = listOf(
CurrencyBalance("btc-bitcoin", "0.31244124"),
CurrencyBalance("eth-ethereum", "0.327834478541236547"),
CurrencyBalance("usdp-paxos-standard-token", "0.31244124")
)
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
)
CodePudding user response:
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