3

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()
1
  • 2
    Not sure completely but newsItems?.distinct() returns new instance of collection. Commented Jun 8, 2018 at 14:47

3 Answers 3

19

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.

Sign up to request clarification or add additional context in comments.

3 Comments

May you please share your solution?
@MatheusRibeiro you should use the return value val newList = items.distinct()
@MMoersalin Yeah, I was too much of a newbie to understand that LOL
3

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.

Comments

0

Also you can try toSet()

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.