Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@martinky
Last active October 28, 2022 11:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save martinky/1291567276d2161896dbb726d8e5774f to your computer and use it in GitHub Desktop.
Save martinky/1291567276d2161896dbb726d8e5774f to your computer and use it in GitHub Desktop.
Kotlin extension function to produce an interleaved flattened list from a collection of iterables
/**
* Produces a flattened [List] that is an interleaved merge of the input iterables.
*
* For example:
*
* ```
* listOf(
* listOf(1, 2, 3, 4),
* listOf('a', 'b')
* ).interleave()
* ```
*
* will produce this list:
*
* ```
* [1, 'a', 2, 'b', 3, 4]
* ```
*/
fun <T> Iterable<Iterable<T>>.interleave(): List<T> {
val result = ArrayList<T>()
val iterators = this.map { it.iterator() }
do {
var hasMore = false
for (i in iterators) {
if (i.hasNext()) {
result.add(i.next())
hasMore = true
}
}
} while (hasMore)
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment