Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
like image 844
theanilpaudel Avatar asked Jan 24 '26 19:01

theanilpaudel


2 Answers

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.

like image 146
yole Avatar answered Jan 26 '26 11:01

yole


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.

like image 20
Simon Avatar answered Jan 26 '26 10:01

Simon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!