Skip to main content

How to join two ArrayLists in Kotlin

How to join two ArrayLists in Kotlin.

Here's a step-by-step tutorial on how to join two ArrayLists in Kotlin:

Step 1: Create two ArrayLists

First, you need to create two ArrayLists that you want to join. Here's an example:

val list1 = arrayListOf("apple", "banana", "cherry")
val list2 = arrayListOf("orange", "grape", "watermelon")

Step 2: Use the plus operator

Kotlin provides the plus operator (+) to concatenate two ArrayLists. You can use it to join the two ArrayLists created in the previous step. Here's an example:

val joinedList = list1 + list2

In this example, the plus operator (+) concatenates list1 and list2 and assigns the result to joinedList.

Step 3: Print the joined ArrayList

You can print the joined ArrayList to verify the result. Here's an example:

println(joinedList)

This will output:

[apple, banana, cherry, orange, grape, watermelon]

Step 4: Join ArrayLists with duplicates

If you want to join the ArrayLists while allowing duplicates, you can use the plus operator twice. Here's an example:

val joinedListWithDuplicates = list1 + list2 + list1

In this example, list1 and list2 are joined, and then list1 is appended again to the result.

Step 5: Print the joined ArrayList with duplicates

You can print the joined ArrayList with duplicates to verify the result. Here's an example:

println(joinedListWithDuplicates)

This will output:

[apple, banana, cherry, orange, grape, watermelon, apple, banana, cherry]

Step 6: Create an empty ArrayList and add elements from both lists

If you want to join the ArrayLists without using the plus operator, you can create an empty ArrayList and add elements from both lists. Here's an example:

val joinedListEmpty = ArrayList<String>()
joinedListEmpty.addAll(list1)
joinedListEmpty.addAll(list2)

In this example, an empty ArrayList joinedListEmpty is created, and elements from list1 and list2 are added using the addAll() method.

Step 7: Print the joined ArrayList created without plus operator

You can print the joined ArrayList created without using the plus operator to verify the result. Here's an example:

println(joinedListEmpty)

This will output:

[apple, banana, cherry, orange, grape, watermelon]

That's it! You have successfully joined two ArrayLists in Kotlin. You can choose the method that suits your requirements and use it in your code.