How to flatten list of list values in groupBy in Kotlin

Viewed 526

I have an object structure

data class File(val travelBatch: List<TravelBatch>) {
    data class TravelBatch(
        val currency: String,
        val transactions: List<Transaction>
    )
}

I want to have a map of currency to transactions. The below code I tried gives Map<String, List<List<Transaction>> I want Map<String, List<Transaction>

file.travelBatch.groupBy({it.currency}, {it.transactions})

Need help to flatten the values in the map in kotlin?

1 Answers

You can use mapValues

val result = file.travelBatch
    .groupBy({ it.currency }, { it.transactions })
    .mapValues { it.value.flatten() }
Related