Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Untested, but I guess it should work:

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading