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()
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With