I have a JSON list, in which I need to filter the data based on some filters.
I was using predicate for filtering, but as per my need I need to filter the nested list, and if here I use predicates I am left with 3 test predicate that's Any, None, and All
but as I want only matched data and which I am not getting using any of these predicates.
As Any
returns true if at least there is one match element, and All
returns true if there are all matched elements but how can I get only the matched elements from the nested list irrespective of any non-matched element.
I can use the traditional approach of looping through the list, but I wanted to know whether it is possible to use a predicate.
Here's the sample JSON
I am trying to get the center whose session elements contains min_age_limit is > 18
and available_dose_1 > 0
.
{
"centers": [
{
....
"sessions": [
{
"session_id":"adad",
...
"min_age_limit":45,
"available_capacity_dose1": 5,
"available_capacity_dose2": 5
...
},
{
"session_id":"adad1",
...
"min_age_limit":18,
"available_capacity_dose1": 0,
"available_capacity_dose2": 5
...
},
{
"session_id":"adad2",
...
"min_age_limit":18,
"available_capacity_dose1": 5,
"available_capacity_dose2": 0
...
}
]
}
....
]
}
It's not possible to use predicates. I transformed the list to a map and then added the filters.
val allValidSessions = it?.data?.centers?.sortedBy { it.name }?.map { center ->
center to center.sessions?.filter { session -> isValidSession(session, 18, selectedDose) }
}?.toMap()
private fun isValidSession(session: Session, s: String, selectedDose: String): Boolean {
if (session.minAgeLimit!! == s.toInt() && (if (selectedDose == "1") session.availableCapacityDose1!! > 0 else session.availableCapacityDose2!! > 0)) return true
return false
}