Reputation: 107
I have two lists
list1 = [ { city: 'Los Angeles', population: '4 million ' } ... ]
list2 = [ { nameOfCity: 'New York', language: 'English' }, {nameOfCity: 'Berlin', language: 'German' ]
Now I need to create a new list and filter the two lists by the name of city and then group it by the same language
newClass(val nameOfCities: List<String>, language: String)
So I need to check if city names of list2 are inside list 2 (list2.filter { it.nameOfCity != list1.city } and store all the names inside the nameOfCities list grouped by language
so the end result should be something like this:
[
{ nameOfCities: [New York, Chicago]
language: Engilsh
},
{ nameOfCities: [Berlin]
language: German
}
]
So I get a new list of all the cities that don't exists in list1 and grouped by the same language.
This is the closest I got:
for (item in list1) {
reducedList = (list2.filter { it.nameOfCity != item.city }.map { newClass(it.nameOfCity, it.language) })
.toList().groupBy { it.language }
}
But the format is like this:
'english': [
{ nameOfCity: 'Los Angeles', language: 'English' },
{ nameOfCity: 'New York', language: 'English' },
],
'german': [ { nameOfCity: 'Berlin ', language: 'German' } ]
Upvotes: 0
Views: 1345
Reputation: 193
Maybe this one will be helpfull:
list2.filter { list2Element -> !list1.any { it.city == list2Element.nameOfCity} }
.groupBy({it.language}, {it.nameOfCity}).map { newClass(it.value, it.key) }
Instead of iterating and filtering you can simply use .any()
Upvotes: 1
Reputation: 516
I'm not sure I understood what you meant but i try to help you:
I am assuming that you have 3 classes like as follow:
class newClass(val nameOfCities: List<String>, val language: String)
class ListElement1(val city: String, val population: String)
class ListElement2(val nameOfCity: String, val language: String)
And 2 lists:
val list1 = listOf(ListElement1("Los Angeles", "4 million"))
val list2 = listOf(ListElement2("New York", "English"), ListElement2("Berlin", "German"))
Filter list2 in order to delete all cities that are in list1 and map all to a list of newClass:
var reducedList: List<NewClass> = listOf()
list1.forEach{ listElement1 ->
= list2.filter { listElement1.city != it.nameOfCity }
.groupBy { it.language }.map { newClass(it.value.map { it.nameOfCity }, it.key) }
}
Result(json):
[
{
language = "English",
nameOfCities= [
"New York"
]
},
{
language = "German",
nameOfCities= [
"Berlin"
]
}
]
Result(Classes):
[
newClass(nameOfCities=[New York], language=English),
newClass(nameOfCities=[Berlin], language=German)
]
Upvotes: 1