Benefits of Groovy inject Method and how to use it

Posted By : Sanjay Saini | 20-Sep-2014

Hi Friends,

In this blog .I am going to explain Use of groovy inject Method. Main purpose of inject() method is  to pass the r of first iteration to next iteration and keep on passing till all the elements of collections are traversed.The inject() method processes any type elements of collection with a closure and construct a return value. The first parameter of the inject() method is the initial value of the results of the second parameter the closure. closure help us to iterate over all of the collection elements.

 

Why we used inject() method on elements of collection instead of each loop ?

 

In each loop or any other loop you need a variable that hold the result and initial value. First with each() and side effect, because we have to declare a variable to hold the result:

 def multiply = 1
(1..5).each { multiply *= it }
assert 120  == multiply

In inject method we 'inject' the initial value of the result, and then for each item the result is increased and returned for the next iteration.

def result = (1..5).inject(1) {multiply, i -> multiply * i }
assert 120 == result

We add a println statement to see the output.

(1..5).inject(1) { multiply, i ->
println "$multiply * $i = ${multiply * i}"
multiply * i
}

ouput of above code snippet :

1 * 1 = 1

1 * 2 = 2

2 * 3 = 6

6 * 4 = 24

24 * 5 = 120

class Student {
String studentName
int rollNo
}
def students = [
new Student(studentName:'Mohit', rollNo:105),
new Student(studentName:'Sanjay', rollNo:106)
]

Convert list to a map where the key is the value of studentName property of Student and the value is the rollNo property of Student. We inject an empty map as the starting point for the result.

def resultMap = students.inject([:]) { result, student ->
result[student.studentName] = student.rollNo
result
}
assert [Mohit:105,Sanjay:106] ==resultMap

 

Hope it is useful for you :)

Thanks

Sanjay Saini

 

 

About Author

Author Image
Sanjay Saini

Sanjay has been working on web application development using frameworks like Java, groovy and grails. He loves listening to music , playing games and going out with friends in free time.

Request for Proposal

Name is required

Comment is required

Sending message..