Home > Blockchain >  how to flatten more than 2 array nested
how to flatten more than 2 array nested

Time:05-14

I'm a newbie at Kotlin. And when I learn about flatten function

Returns a single list of all elements from all arrays in the given array.

It is description of that.It work in array nested array. But, how about more than 3 array. Like :

val testArray = listOf(listOf(1,2,3), listOf(4,3,9, listOf(3,3,6)))

Output I want is:

[1, 2, 3, 4, 3, 9, 3, 3, 6]

So, anyone can help me ? Thanks.

CodePudding user response:

This should work with the countless nested arrays.


fun <T> Iterable<T>.enhancedFlatten(): List<T> {
    val result = ArrayList<T>()
    for (element in this) {
        if (element is Iterable<*>) {
            try {
                result.addAll(element.enhancedFlatten() as Collection<T>)
            } catch (e: Exception) {
                println(e)
            }
        } else {
            result.add(element)
        }
    }
    return result
}

CodePudding user response:

fun List<*>.deepFlatten(): List<*> = this.flatMap { (it as? List<*>)?.deepFlatten() ?: listOf(it) }
  • Related