Ivana
Ivana

Reputation: 17

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.

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
)

Upvotes: 1

Views: 674

Answers (1)

Ivo
Ivo

Reputation: 23144

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

Upvotes: 1

Related Questions