Kotlin Flatten List – Problem & Solution
https://grokonez.com/kotlin/kotlin-flatten-list-problem-solution
In the tutorial, JavaSampleApproach will introduce Kotlin flatten()
and the limit of the method. So we will provide a new Flatten Solution for Kotlin List.
I. Kotlin List flatten()
1. flatten() method
Kotlin provides a method to flatten a List:
public fun Iterable>.flatten(): List
-> Returns a single list of all elements from all collections in the given collection.
Practice:
data class Customer(
val name: String,
val age: Int
)
fun main(args : Array){
val list = listOf(
listOf(1, 2, 3),
listOf("one", "two", "three"),
listOf(Customer("Jack", 25), Customer("Peter", 31), Customer("Mary", 18))
)
var flattenList = list.flatten()
println(list)
/*
[[1, 2, 3], [one, two, three], [Customer(name=Jack, age=25), Customer(name=Peter, age=31), Customer(name=Mary, age=18)]]
*/
println(flattenList)
/*
[1, 2, 3, one, two, three, Customer(name=Jack, age=25), Customer(name=Peter, age=31), Customer(name=Mary, age=18)]
*/
}
2. Problem
More at:
https://grokonez.com/kotlin/kotlin-flatten-list-problem-solution
Top comments (0)