kotlincartesian-product

Better way to combine in Kotlin?


I want to combine all elements from one list with all elements from another list, to obtain all possible pairs.

Of course, we can do this in a loop (not tested):

val list1 = listOf(1, 2, 3)
val list2 = listOf('A', 'B', 'C')

val result = mutableListOf<Pair<Int, Char>>()

for (item1 in list1) {
    for (item2 in list2) {
        result.add(Pair(item1, item2))
    }
}

println(result)

Is there a better solution with build-in functions like zip?


Solution

  • Untested, but I guess it should work:

    val result = list1.flatMap { item1 ->
        list2.map { item2 ->
            Pair(item1, item2)
        }
    }