theanilpaudel
theanilpaudel

Reputation: 3478

Distinct not working for ArrayList in Kotlin

I am trying to remove duplicates from an ArrayList in Kotlin. First of all I am getting a sortedNews from somewhere else and then I am adding it to the list called newsItems and then I am trying to remove the duplicates but the duplicates are still there. What am I doing wrong here

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

Upvotes: 3

Views: 8917

Answers (3)

Simon
Simon

Reputation: 2733

The best way would be to, instead of addAll use the function union

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 - Returns a set containing all distinct elements from both collections.

The returned set preserves the element iteration order of the original array. Those elements of the other collection that are unique are iterated in the end in the order of the other collection.

To get a set containing all elements that are contained in both collections use intersect.

Upvotes: 3

MohammadAli
MohammadAli

Reputation: 3456

Also you can try toSet()

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

Upvotes: 0

yole
yole

Reputation: 97128

distinct does not remove duplicates from the collection, it returns a new collection with duplicates removed. You're ignoring the return value of distinct, so the call has no effect.

Upvotes: 19

Related Questions