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
Asked
Active
Viewed 2,776 times
1 Answers
2
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
}

Juan Rada
- 3,513
- 1
- 26
- 26
-
2Thanks for the answer. But if the arrays are of different lengths, then one element will not be added to the result array. – testovtest Mar 22 '21 at 08:09
-
1The 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. – Adam Millerchip Mar 25 '21 at 07:33