Home > Mobile >  How to transter item from list to another list Kotlin
How to transter item from list to another list Kotlin

Time:10-08

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
}

CodePudding user response:

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 }

CodePudding user response:

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 }
  • Related