Thursday 24 January 2019

Groovy: List: inject: Perform reduce operation


public Object inject(Closure closure)
public Object inject(Object initialValue, Closure closure)
Above functions perform the reduction operation. First overloaded form of the function takes head of the collection as initial value.

HelloWorld.groovy

result1 = [ 1, 2, 3, 4].inject { acc, val -> acc * val }
result2 = [ 1, 2, 3, 4].inject { acc, val -> acc + val }

result3 = [ 1, 2, 3, 4].inject(100) { acc, val -> acc * val }
result4 = [1, 2, 3, 4].inject('Appending -> ') { str, item -> str + item }

println "result1 : $result1"
println "result2 : $result2"
println "result3 : $result3"
println "result4 : $result4"

Output
result1 : 24
result2 : 10
result3 : 2400
result4 : Appending: 1234


Previous                                                 Next                                                 Home

No comments:

Post a Comment