Pawan Gorai
06/01/2021, 10:03 AMAny, 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 using 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
...
}
]
}
....
]
}
bsimmons
06/01/2021, 12:58 PMList<Session>
and it should become much simpler.Pawan Gorai
06/01/2021, 4:06 PMdata class
for this JSON.
here it goes
data class Center(
@SerializedName("name")
val name: String?,
@SerializedName("address")
val address: String?,
@SerializedName("pincode")
val pincode: Int?,
@SerializedName("fee_type")
val feeType: String?,
@SerializedName("sessions")
var sessions: List<Session>?
)
But I not getting how can I add a filter to the session list, I need to loop through every center. But I am couldn't able to do.bsimmons
06/01/2021, 5:19 PMfun isValidSession(session: Session) = session.minAgeLimit > 18 && session.availableDose > 0
val centersWithAtLeastOneValidSession = centers.filter { center ->
center.sessions.any { session -> isValidSession(session) }
}
Pawan Gorai
06/01/2021, 6:20 PMAny
will give the session list if at least one of the sessions satisfies the condition so it ends up with some invalid session too which doesn't satisfy the conditions.
But I want only the matched sessions.bsimmons
06/01/2021, 6:33 PMval allValidSessions = centers.map { center ->
center.sessions.filter { session -> isValidSession(session)}
}.flatten()
bsimmons
06/01/2021, 6:34 PMbsimmons
06/01/2021, 6:38 PMCenter
itself to make things more intuitive. (i.e.):
data class Center(
/* other properties .... */
val sessions: List<Session>
) {
fun hasValidSession() = sessions.any(::isValidSession)
fun getValidSessions() = sessions.filter(::isValidSession)
}
Pawan Gorai
06/02/2021, 6:16 AMval allValidSessions = it?.data?.centers?.sortedBy { it.name }?.map { center ->
center to center.sessions?.filter { session -> isValidSession(session, prefAge[0], selectedDose) }
}?.toMap()