How to get the amounts for all elements from two lists in Kotlin?

In Kotlin, I have two lists:

val x: List<Int> = listOf(1,2,3,4,5,6)
val y: List<Int> = listOf(2,3,4,5,6,7)

How do I get:

val z: List<Int> = 3,5,7,9,11,13

without using loops?

+4
source share
2 answers

Assuming both lists are the same size :

  • Using zip

    val sum = x.zip(y) { xv, yv -> xv + yv }
    
  • Using simple mapandmapIndexed

    val sum = (0 until x.size).map { x[it] + y[it] }
    // or
    val sum = x.mapIndexed { index, xv -> xv + y[index] }
    

When the size may differ and you would take 0 for entries out of range:

  • Using array

    val sum = IntArray(maxOf(x.size, y.size)) { 
        x.getOrElse(it, {0}) + y.getOrElse(it, {0}) 
    }.toList()
    
  • Range Usage:

    val sum = (0 until maxOf(x.size, y.size)).map { 
        x.getOrElse(it, {0}) + y.getOrElse(it, {0})
    }
    
  • Expanding Lists to Same Size

    val xExtended = x + Array(maxOf(0, y.size - x.size), { 0 })
    val yExtended = y + Array(maxOf(0, x.size - y.size), { 0 })
    val sum = xExtended.zip(yExtended) { xv, yv -> xv + yv }
    
+8
source

I would go with a range and map:

val sums = (0 until x.size).map { x[it] + y[it] }

This is probably less overhead than zip.

+2
source

Source: https://habr.com/ru/post/1692670/


All Articles