yuta yanagisawa
yuta yanagisawa

Reputation: 71

How to transter item from list to another list Kotlin

Hi is there simple way to transfer an item from list to another list in kotlin?

currently I'm doing it this way.

val list = mutableListOf(1,2,3,4,5,6)
val oddList = mutableListOf<Int>()

oddList.addAll(
  list.filter {
    it % 2 = 1
  }
)

list.removeIf {
  it % 2 = 1
}

Upvotes: 0

Views: 62

Answers (2)

Arpit Shukla
Arpit Shukla

Reputation: 10493

If you want to modify existing MutableLists, an alternative way can be:

val itemsToTransfer = list.filter { it % 2 == 1 }
oddList += itemsToTransfer
list -= itemsToTransfer

If you want to just separate out odd and even elements into new lists, you can use the partition function.

val (even, odd) = list.partition { it % 2 == 0 }

Upvotes: 3

somethingsomething
somethingsomething

Reputation: 2165

Sounds to me like you are looking for the partition method: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/partition.html

Would be something like this

val (oddList, list) = list.partition { it % 2 == 1 }

Upvotes: 2

Related Questions