'how to flatten more than 2 array nested
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.
Solution 1:[1]
fun List<*>.deepFlatten(): List<*> = this.flatMap { (it as? List<*>)?.deepFlatten() ?: listOf(it) }
Solution 2:[2]
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
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | lukas.j |
Solution 2 | Enes Kay?kl?k |