Flat family

Say you have a list of other lists. You probably got it from different database queries, or maybe from different configuration files:

val listOfLists = listOf(listOf(1, 2),
listOf(3, 4, 5), listOf(6, 7, 8))

// [[1, 2], [3, 4, 5], [6, 7, 8]]

And you want to turn them into a single list such as the following:

[1, 2, 3, 4, 5, 6, 7, 8]

One way to merge those lists is to write some imperative code:

val results = mutableListOf<Int>()

for (l in listOfLists) {
results.addAll(l)
}

But calling flatten() will do the same for you:

listOfLists.flatten()

You can also control what happens with those results using flatMap():

println(listOfLists.flatMap {
it.asReversed()
})

Note that in this case, it refers to one of the sublists. 

You can also decide to use flatMap() for type conversions:

println(listOfLists.flatMap {
it.map { it.toDouble() }
// ^ ^
// (1) (2)
})

The preceding code prints the following output:

[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0]

We converted all integers to doubles, and then merged them into a single list.

Note how the first it refers to one of the lists, while the second it refers to a single item inside the current list.

As far as flatten() goes, it flattens only one level down. To demonstrate that, we'll use Set for the first level of nesting, List for the second level of nesting, and Set again for the third level of nesting:

val setOfListsOfSets = setOf(
// ^
// (1)
listOf(setOf(1, 2), setOf(3, 4, 5), setOf(6, 7, 8)),
// ^ ^
// (2) (3)
listOf(setOf(9, 10), setOf(11, 12))
// ^ ^
// (2) (3)
)
// Prints [[[1, 2], [3, 4, 5], [6, 7, 8]], [[9, 10], [11, 12]]]

If we call flatten once, we receive only the first level flattened:

println(setOfListsOfSets.flatten())

The preceding code prints the following output:

[[1, 2], [3, 4, 5], [6, 7, 8], [9, 10], [11, 12]]

To completely flatten the list, we need to call flatten() twice:

println(setOfListsOfSets.flatten().flatten())

The preceding code prints the following output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

Kotlin prevents us from calling flatten() three times, as it recognizes the amount of nesting we have:

//Won't compile
println(setOfListsOfSets.flatten().flatten().flatten())
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.227.79.241