testovtest
testovtest

Reputation: 171

Kotlin. Merge two list with alternating values

Is there a ready-made solution for creating an list by alternating elements from two list. I understand how this can be done using loops and conditions, but perhaps there is a ready-made extension that will allow you to solve the problem concisely

Upvotes: 0

Views: 3421

Answers (1)

Juan Rada
Juan Rada

Reputation: 3786

You can use zip and flatMap result.

    val list1 = listOf(1, 2, 3)
    val list2 = listOf(4, 5, 6)
    val result = list1.zip(list2).flatMap { pair -> listOf(pair.first, pair.second) }

note that this solution executes extra memory allocation for each pair so my recommendation is still to implement your own version.

fun <T> List<T>.mix(other: List<T>): List<T> {
    val first = iterator()
    val second = other.iterator()
    val list = ArrayList<T>(minOf(this.size, other.size))
    while (first.hasNext() && second.hasNext()) {
        list.add(first.next())
        list.add(second.next())
    }
    return list
}

Upvotes: 3

Related Questions