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
1 Answer
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
}
2 Comments
testovtest
Thanks for the answer. But if the arrays are of different lengths, then one element will not be added to the result array.
Adam Millerchip
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.