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

How to get collection values in Kotlin lambda

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:

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

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

>Solution :

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 }
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