0

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

0

1 Answer 1

3

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer. But if the arrays are of different lengths, then one element will not be added to the result array.
The question only asks for a library function for "alternating elements" and does not specify what to do when there are extra elements. This answer answers the question asked, IMO.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.