Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over list with lambda forEach Kotlin

I have a list of 30 random numbers that correspond to 1 of 8 colours, and I need to iterate over the 8 colors(or 30 numbers) and find the number of times each colour occurs. I need to do this using lambdas and functional programming, so no traditional for loops.

val iterator = colours.toList().iterator()

iterator.forEach{

    println("$it count: " + (numbers
            .map{a -> colours[a]}
            .count{it == ("$it")}))
}

The problem currently is my output for count is just 50, not the specific number of times a colour occurs.

If I do it like this:

println("Red count:" +    (numbers
        .map{a -> colours[a]}
        .count{it ==  ("red")}))

it outputs the correct number, but not with the loop.

What it ouputs:

green count: 50 

red count: 50

what it should output (for example)

green count:9

red count:3

Thanks in advance

like image 964
user7327019 Avatar asked Mar 13 '26 03:03

user7327019


1 Answers

Add a named parameter to your forEach loop. The implicit name "it" is getting shadowed by the count function.

val iterator = colours.toList().iterator()

iterator.forEach { colour ->

    println("$colour count: " + (numbers
        .map{a -> colours[a]}
        .count{it == ("$colour")}))
}
like image 81
Damon Baker Avatar answered Mar 14 '26 16:03

Damon Baker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!