Home > Mobile >  Kotlin filtering nested lists with other list
Kotlin filtering nested lists with other list

Time:11-03

I have a list like this:

val list = List<FlightRecommendationQuery>

in that:

data class FlightRecommendationQuery(
 val segments: List<Segment>
)

data class Segment(
 val stops: Int
)

I have another list with size same as segments size in FlightRecommendationQuery called filter:

val filter = List<Filter>

data class Filter(
 val stops: Int
)

I want to filter 'list' when filter's stops are equal to each segments in list. Here, size of list 'filter' and size of 'segments' of FlightRecommendationQuery are same.

CodePudding user response:

I'm not sure if there is a more efficient way to do it but I think this would do it:

val filteredList = list.filter { it.segments.map { it.stops }.equals(filter.map { it.stops }) }

CodePudding user response:

Here's a Kotlin solution if I understood your question correctly

fun main() {

    // DATA SETUP 
    
    val s1 = Segment(1)
    val s2 = Segment(2)
    val s3 = Segment(3)

    val segmentList = listOf(s1,s2,s3)
    val query = FlightRecommendationQuery(segmentList)

    val f1 = Filter(1)
    val f2 = Filter(9999)
    val f3 = Filter(3)

    val filterList = listOf(f1,f2,f3)
    // END OF DATA SETUP 
    
    // Here we do the filtration
    val filteredSegments = mutableListOf<Segment>()
    for(segmentIndex in query.segments.indices) {
        // We use indices concept from Kotlin to get the items in the same 
        // position from both lists
        val segment = query.segments[segmentIndex]
        val filter = filterList[segmentIndex]

        if(segment.stops == filter.stops) filteredSegments.add(segment)
    }

    //Filtered segments now contains the necessary data
    //Will print [Segment(stops=1), Segment(stops=3)] in this case
    //Use this list of segments to create a new FlightRecommendationQuery
    println(filteredSegments)
}

CodePudding user response:

You can do this by zipping segments and filter and checking if all of them are equal:

list.filter { query ->
    (query.segments zip filter)
        .all { it.first.stops == it.second.stops }
}

CodePudding user response:

Another way:

list.filter { query ->
    filter.indices.all { filter[it].stops == query.segments[it].stops }
}

all returns true if all the elements of list match the given predicate

  • Related