Using Inject method in Groovy 2.0

26 / Sep / 2012 by Divya Setia 2 comments

A very useful enhanced method in Groovy 2.0 is inject method whose key purpose is to pass the outcome of first iteration to next iteration and keep on passing till all the elements of collections are processed.

Lets start with an example, consider a class Employee with name and salary as attributes:

[java]
class Employee{
String name
Float salary
}

Employee emp1 = new Employee(name:"Divya",salary:50000)
Employee emp2 = new Employee(name:"Priya",salary:30000)
Employee emp3 = new Employee(name:"Ginny",salary:60000)
Employee emp4 = new Employee(name:"Shreya",salary:80000)
Employee emp5 = new Employee(name:"Heena",salary:10000)

List<Employee> employees = [emp1,emp2,emp3,emp4,emp5]
[/java]

And if we have to find out sum of salaries of those employees whose salary is greater than 40000, then most cleaner way of doing the same is using the inject method which also prevent us to define a new variable for doing the same.

[java]
Float totalSalaryOfUsers = employees*.salary.inject{accumulator,currentValue-> accumulator + (currentValue > 40000 ? currentValue : 0) }

println totalSalaryOfUsers

// Output : 190000.0
[/java]

In previous version of Groovy(<2.0), there was need to initialize the inject method with a value, but in Groovy 2.0, inject method initializes itself with the first element of collection.

Consider one more example of inject method for clear understanding, i.e. ,converting list to String is:

[java]
List<String> thought = ["Don’t","put","off","till","tomorrow","what","you","can","do","today"]

String strThought = thought.inject{accumulator,currentValue-> accumulator + " " + currentValue }

println strThought

// Output: Don’t put off till tomorrow what you can do today

[/java]

FOUND THIS USEFUL? SHARE IT

comments (2)

  1. zdezynfekowanie

    At this time it appears like Expression Engine is the best blogging platform out there right now. (from what I’ve read) Is that what you are using on your blog?

    Reply

Leave a Reply to Lari H Cancel reply

Your email address will not be published. Required fields are marked *