1

hello I would like to know which is the best performance to join two mutables list

if list1.addall (list2) with foreach list1?.let { list1 -> list2?.let(list1::addAll) }

or a map or something like that..?

dasuma
  • 781
  • 1
  • 6
  • 12

4 Answers4

2

If the first list is mutable and you want to modify it, just use += operator:

list1 += list2

It delegates to addAll member function, appending all elements of list2 to list1

If you don't want to mutate the original list, use + operator:

val result = list1 + list2

It concatenates two lists into the third new list. Compared to creating an empty ArrayList by hand and calling addAll on it, this operator has an advantage of presizing the resulting ArrayList to an estimated size, so it helps to spare ArrayList's storage array reallocations.

Ilya
  • 21,871
  • 8
  • 73
  • 92
1

If list1 is mutable and you can modify it:

list1.addAll(list1.size, list2)

and in list1 you will have list1 + list2

If you can not modify you can create ArrayList or LinkedList and add all

val newList = ArrayList<Int>()

newList.addAll(list1)
newList.addAll(list2)
Boken
  • 4,825
  • 10
  • 32
  • 42
1

If both of them are of same type, then you can use flat map in Kotlin. For example,

val listA = mutableList<String>()
val listB = mutableList<String>()

Then you can merge both of them like below

val mergedList = listOf(listA, listB).flatten()

or

val mergedList = listOf(listA, listB).flatMap { it }

This way it's efficient, more readable and less code!! Happy coding with kotlin!

Varun A M
  • 1,103
  • 2
  • 14
  • 29
-1

The best option is to create a LinkedList because it's always cheap to add items into it, whereas an ArrayList might sometimes allocate more space if you reach the end of the array.

See this for more info on the topic When to use LinkedList over ArrayList in Java?

If list1 isn't a LinkedList already, keeping in mind mutableListOf() returns an ArrayList, then you can create a third list like so:

 val newList = LinkedList<Int>()
    list1.forEach {
        newList += it
    }

    list2.forEach {
        newList += it
    }
Benoit TH
  • 601
  • 3
  • 12