Search code examples
kotliniteratorsetsubsetpairwise

Kotlin: Iterate through every pair (or generally fixed-sized subsets) in collection


Is there a short/idiomatic way to iterate through every pair of elements in a collection?

Even better would be a method that iterates through all fixed-cardinality subsets of a collection.

The classic and ugly approach would be:

val s = setOf(1, 2, 3, 4)

for (i in s) {
    for (j in s) {
        if (i != j) {
            println("$i $j")
        }
    }
}

For having bigger subsets, more loops are necessary, so this isn't scalable.


Solution

  • I think you got already the most idiomatic way to solve it. If you want to do it more functional, this is what you can convert it to:

    s.map { i -> s.map { i to it } }
        .flatten()
        .filter { (left, right) -> left != right }
        .onEach { (i, j) -> println("$i $j") }