Saturday, 26 January 2019

Groovy: Count number of values that matches to given predicate


public Number count(Closure closure)
Counts the number of occurrences which satisfy the given closure from inside this Iterable.

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

matchedNumbers = numbers.count {it % 2 == 0}
println "Total even Numbers : $matchedNumbers"

matchedNumbers = numbers.count {it % 2 != 0}
println "Total odd Numbers : $matchedNumbers"

Output
Total even Numbers : 6
Total odd Numbers : 9


Previous                                                 Next                                                 Home

No comments:

Post a Comment