Home > Back-end >  How to get collection values in Kotlin lambda
How to get collection values in Kotlin lambda

Time:06-22

I have two collections: A and B. Both of them consist of equal amount of chars. I zip them. Then I need to count pairs of the same elements, like 'A' and 'A'. I need to write a predicate, but I can't find the way to get both elements from a zipped collection. I've tried something like this:

    val num = A.zip(B).count { it.i: Int, it.j:Int -> it.i == it.j}

and this:

    val num = A.zip(guess).count { it[0] == it[2] }

But it doesn't work. How can I reach both elements from these sub lists of chars? I looked into Kotlin official examples but there are only easy ones:

val evenCount = numbers.count { it % 2 == 0 }

CodePudding user response:

In order to deconstruct the resulting Pair given by .zip when using .count, you need to put the "deconstructor" into parentheses.

a.zip(b).count { (aElement, bElement) -> aElemant == bElement }

You could also just ignore that and just access it directly.

a.zip(b).count { it.first == it.second } 

CodePudding user response:

If you want to count the pairs of elements in two lists, you're very close. By calling zip you are given a Pair. You can count the resulting list of Pair objects by accessing their first and second parts and seeing if they match (using ==).

// Assumptions...
val a = listOf("A", "B", "D")
val b = listOf("A", "B", "C")

// Count where both elements of the zipped pair match
return a.zip(b).count { it.first == it.second }
  • Related