【问题标题】:Distinct not working for ArrayList in Kotlin不同的不适用于 Kotlin 中的 ArrayList
【发布时间】:2018-06-08 14:42:27
【问题描述】:

我正在尝试从 Kotlin 中的 ArrayList 中删除重复项。首先,我从其他地方得到一个 sortedNews,然后我将它添加到名为 newsItems 的列表中,然后我试图删除重复项,但重复项仍然存在。我在这里做错了什么

sortedNewsItems = nsItems!!.sortedWith(compareByDescending({it!!.timeStamp}))
        newsItems?.addAll(sortedNewsItems!!)
        newsItems?.distinct()
        Log.e("first item name ",sortedNewsItems?.get(0)?.title)
        recyclerView.adapter.notifyDataSetChanged()

【问题讨论】:

  • 不完全确定,但newsItems?.distinct() 返回集合的新实例。

标签: android arraylist kotlin


【解决方案1】:

distinct 不会从集合中删除重复项,它会返回一个删除了重复项的新集合。您忽略了distinct 的返回值,因此调用无效。

【讨论】:

  • 能否分享一下您的解决方案?
  • @MatheusRibeiro 你应该使用返回值val newList = items.distinct()
  • @MMoersalin 是的,我是新手,无法理解 LOL
【解决方案2】:

最好的方法是使用函数union 而不是addAll

val firstList: ArrayList = arrayListOf(1, 2, 3, 4)
val secondList: ArrayList = arrayListOf(1, 5, 6, 7, 8)

val addAllList = firstList.addAll(secondList) //1,2,3,4,1,5,6,7,8
val unionList = firstList.union(secondList) //1,2,3,4,5,6,7,8

union - 返回一个集合,其中包含来自两个集合的所有不同元素。

返回的集合保留原始的元素迭代顺序 大批。其他集合中独特的元素是 最后按照其他集合的顺序迭代。

获取一个集合,其中包含两者中包含的所有元素 集合使用相交。

【讨论】:

    【解决方案3】:

    你也可以试试toSet()

    val newItems = postList //postList id old list
    newItems.addAll(_postList) // _postList is new list
    postList = newItems.toSet().toMutableList()
    

    【讨论】:

      猜你喜欢
      • 2018-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-27
      • 1970-01-01
      • 2018-07-11
      • 2019-10-28
      • 1970-01-01
      相关资源
      最近更新 更多