7

I am trying to copy one ArrayList to another ArrayList in Kotlin

1st ArrayList:

private var leadList1: ArrayList<Lead> = ArrayList()

2nd ArrayList:

val leadList2: ArrayList<Lead?>?

I tried to use addAll(). leadList1.addAll(leadList2)

But its not working.

Error showing:

Required: Collection<Lead>
Found: kotlin.collections.ArrayList<Lead?>?

3 Answers 3

19

This isn't safe to do, because your first list can only contain objects of type Lead, while your second one has Lead? as its type parameter, meaning that it might contain null values. You can't add those to the first list.

The solution for this problem will depend on your context, but you can either let the first list contain nullable elements too:

private var leadList1: ArrayList<Lead?> = ArrayList()

Or you can add only the non-null elements of the second list to the first one:

leadList1.addAll(leadList2.filterNotNull())

And in either case, you'll have to perform a null check on leadList2, because the entire list itself is marked as potentially null as well, signified by the last ? of the type ArrayList<Lead?>?.

if (leadList2 != null) {
    leadList1.addAll(leadList2.filterNotNull())
}
Sign up to request clarification or add additional context in comments.

Comments

8

You can simply pass another List instance into the constructor of your new List

val originalList = arrayListOf(1,2,3,4,5)

val orginalListCopy = ArrayList(originalList)

Comments

1

Do this: leadList1.addAll(leadList2.orEmpty().filterNotNull())

And to filter by property you can do like this:

leadList1.addAll(leadList2.orEmpty().filter { item -> item?.type == YourTypeString })

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.