【问题标题】:Is there a way to do multiple filtering in Kotlin?有没有办法在 Kotlin 中进行多重过滤?
【发布时间】:2021-09-09 01:09:52
【问题描述】:

我正在为 android 创建一个播客应用程序。我想过滤播客列表,所以我只能获得健康类型。但是大约有 3 种不同的健康类型。我决定过滤所有这三个。现在,每当我运行该应用程序时,都会显示一个空列表。但是,如果我只过滤一种健康类型,那么一切正常。这是我的代码。

suspend fun getHealthPodcast(): List {

    val requireGenreHF =Genre("1512", "Health & Fitness","https://itunes.apple.com/gb/genre/id1512")
    val requireGenreAH =Genre("1513", "Alternative Health","https://itunes.apple.com/gb/genre/id1513")
    val requireGenreMH =Genre("1517", "Mental Health","https://itunes.apple.com/gb/genre/id1517")

    val listGenre = listOf(requireGenreHF, requireGenreAH, requireGenreMH)

    val results = itunesRepo?.getHealthPodcast()

    if (results != null && results.isSuccessful) {

        val podcasts = results.body()?.feed?.results

        val filteredData = podcasts?.filter {
            it.genres.containsAll(listGenre)
        }
        if (filteredData != null) {
            return filteredData.map { podcast ->
                itunesPodcastView(podcast)
            }
        }
    }
    return emptyList()
}

【问题讨论】:

    标签: android kotlin mvvm retrofit2


    【解决方案1】:

    containsAll() 要求genres 包含listGenre所有 元素,因此必须将播客同时标记为每个健康类型。如果您想搜索任何健康的流派,您可以这样做:

    it.genres.any { it in listGenre }
    

    【讨论】:

    • 你的回答很成功。再次感谢
    【解决方案2】:

    让我们深入研究您的代码。

    我正在为 android 创建一个播客应用程序。我想过滤播客列表,所以我只能获得健康类型。但是大约有 3 种不同的健康类型。我决定过滤所有这三个。现在,每当我运行该应用程序时,都会显示一个空列表

    现在让我们看看这条线

    val filteredData = podcasts?.filter {
                it.genres.containsAll(listGenre)
            }
    

    如果您深入了解containsAll 方法的documentation。这是定义的

    检查指定集合中的所有元素是否都包含在此集合中。

    所以事情是它确保它过滤具有所有可能不存在的指定类型的元素,因此你得到一个空列表。

    现在找到答案和您的解决方案,您需要的是简单或条件

    val filteredData = podcasts?.filter {
                it.genres.contains(requireGenreHF) || it.genres.contains(requireGenreAH) || it.genres.contains(requireGenreH)
            }
    

    还有很多过滤方法,比如any 调用,你可以研究一下。它们更加精致。

    【讨论】:

    • 我这样做了,但没有添加 ||。现在会添加它谢谢队友
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-25
    • 2012-09-23
    • 2012-01-20
    相关资源
    最近更新 更多