PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, November 4, 2022

[FIXED] How to get collection values in Kotlin lambda

 November 04, 2022     kotlin, lambda     No comments   

Issue

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 }

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 }


Answered By - Todd
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing