https://kotlinlang.org logo
Title
d

Daniele B

08/13/2020, 2:24 PM
I have 2 different lists: listA has objA elements, with these properties: country, language listB has objB elements, with these properties: country, population I would like to merge them by creating listC, with properties: country, language, population How can I do that?
d

diesieben07

08/13/2020, 2:29 PM
val languages = listOf<A>()
    val populations = listOf<B>()
    val populationsByCountry = populations.associateBy { it.country }
    val result = languages.map { C(it.country, it.language, checkNotNull(populationsByCountry[it.country]).population) }
👍 2
d

Daniele B

08/13/2020, 2:34 PM
Oh, I see, very interesting. AssociateBy is creating a map out of the list. Great! Many thanks!
n

nanodeath

08/13/2020, 3:08 PM
another heavier way, but a little more flexible way, is to call associateBy on both lists, and then say
(populationsByCountry.keySet + languagesByCountry.keySet).map { ... }
. then you can error if an item is missing from either collection.
👍 1