I have 2 different lists: listA has objA elements...
# getting-started
d
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
Copy code
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
Oh, I see, very interesting. AssociateBy is creating a map out of the list. Great! Many thanks!
n
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