【问题标题】:Kotlin filter methodKotlin 过滤方法
【发布时间】:2021-05-28 20:35:09
【问题描述】:

我有一个 10 号的 ID 列表 我还有另一个项目列表,我想要一种有效的方法来删除与这 10 个 id 中的任何一个匹配的项目

  val list=items.filter { id== 1||id==3... and so on but in a more efficient way } 

提前致谢

【问题讨论】:

    标签: android dictionary kotlin filter


    【解决方案1】:

    你可以使用谓词和filterTo方法

    //list of things you don't want in your filtered list
     val listOfIds= listOf(312,264,309,297,233,262,149,156,214,350,316,315)
    //a predicate used in filterTo function
      private val someFilteringCondition = { num: Int ->listOfIds.contains(num) }
    
    //list that we will filter into (it will contains filtered list
    private val filteredPublishers = mutableListOf<SegmentModel>()
    
     items.filterNotTo(filteredPublishers,someFilteringCondition )
                            adpater?.publishersChanged(it)
    

    现在过滤的发布者列表包含未提及 ID 的项目

    【讨论】:

      【解决方案2】:

      如果您正在处理MutableList,您可以使用removeAllretainAll 方法修改它(或它的副本):

      保留ids 中不存在于removeIds 中的所有项目:

      fun main() {
          val ids = mutableListOf(20, 30, 40, 42, 50, 60)
          val removeIds = listOf(20, 30, 40, 50, 60)
          ids.retainAll { it !in removeIds }
          println(ids)
      }
      

      或从ids 中删除removeIds 中存在的所有项目:

      fun main() {
          val ids = mutableListOf(20, 30, 40, 42, 50, 60)
          val removeIds = listOf(20, 30, 40, 50, 60)
          ids.removeAll { it in removeIds }
          println(ids)
      }
      

      在这些示例中,mains 都将 ids 简化为 [42],并准确输出。

      不幸的是,这不适用于不可变的Lists,您必须先将其设为MutableList,最好使用toMutableList() 或类似的东西。

      【讨论】:

        【解决方案3】:

        返回一个列表,其中包含原始集合的所有元素,但给定元素集合中包含的元素除外:

        fun main() {
            val ids = listOf(20, 30, 40, 50, 60)
            val removeIds = listOf(30, 60)
            val result = ids - removeIds
            println(result)   // [20, 40, 50]
        }
        

        或者用减法:

        val result = ids subtract removeIds
        

        【讨论】:

          猜你喜欢
          • 2021-11-12
          • 1970-01-01
          • 2019-08-27
          • 1970-01-01
          • 1970-01-01
          • 2020-02-07
          • 1970-01-01
          • 1970-01-01
          • 2023-01-12
          相关资源
          最近更新 更多