Saturday 26 January 2019

Groovy: list: Count number of occurrences of given value


Groovy provides count method that takes a value as an argument and return number of occurrences of this value.

public Number count(Object value)
Counts the number of occurrences of the given value inside this Iterable. It compares the values using == operator.

HelloWorld.groovy
numbers = [1, 3, 3, 3, 2, 1, 4, 5, 4, 3, 2, 1, 6, 7, 8]

repeated = numbers.count(3)
println "3 repeated $repeated times in $numbers"

repeated = numbers.count(1)
println "1 repeated $repeated times in $numbers"

repeated = numbers.count(10)
println "10 repeated $repeated times in $numbers"

Output
3 repeated 4 times in [1, 3, 3, 3, 2, 1, 4, 5, 4, 3, 2, 1, 6, 7, 8]
1 repeated 3 times in [1, 3, 3, 3, 2, 1, 4, 5, 4, 3, 2, 1, 6, 7, 8]
10 repeated 0 times in [1, 3, 3, 3, 2, 1, 4, 5, 4, 3, 2, 1, 6, 7, 8]


Previous                                                 Next                                                 Home

No comments:

Post a Comment