Issue
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)
}
}
Answered By - Nikolas Charalambidis
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.