W3cubDocs

/Kotlin

flatMapIndexed

Platform and version requirements: JVM (1.4), JS (1.4), Native (1.4)
@JvmName("flatMapIndexedIterable") fun <T, R> Sequence<T>.flatMapIndexed(
    transform: (index: Int, T) -> Iterable<R>
): Sequence<R>
@JvmName("flatMapIndexedSequence") fun <T, R> Sequence<T>.flatMapIndexed(
    transform: (index: Int, T) -> Sequence<R>
): Sequence<R>

Returns a single sequence of all elements yielded from results of transform function being invoked on each element and its index in the original sequence.

The operation is intermediate and stateless.

import kotlin.test.*

fun main(args: Array<String>) {
//sampleStart
val data: List<String> = listOf("Abcd", "efgh", "Klmn")
val selected: List<Boolean> = data.map { it.any { c -> c.isUpperCase() } }
val result = data.flatMapIndexed { index, s -> if (selected[index]) s.toList() else emptyList() }
println(result) // [A, b, c, d, K, l, m, n]
//sampleEnd
}

© 2010–2020 JetBrains s.r.o. and Kotlin Programming Language contributors
Licensed under the Apache License, Version 2.0.
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.sequences/flat-map-indexed.html