FindResults and FindResult Methods of Groovy

26 / Sep / 2012 by Vivek Sachdeva 3 comments

In almost all the applications that we work on, we have to transform elements of a collection in one way or the other. We can do it in different ways.

Let there be a domain “Employee” with following attributes:

class Employee{
String firstName
String lastName
Double salary
}

And we have 5 Employees:

Employee employee1 = new Employee(firstName:"John", lastName:"Doe", salary:10000)
Employee employee2 = new Employee(firstName:"Tim", lastName:"Kerry", salary:20000)
Employee employee3 = new Employee(firstName:"Kim", lastName:"Terry", salary:30000)
Employee employee4 = new Employee(firstName:"Mary", lastName:"Jin", salary:40000)
Employee employee5 = new Employee(firstName:"James", lastName:"Sally", salary:50000)

If we want full name of all the employees having salary greater than 25000.
If we use collect in following way:

println Employee.list().collect{it.salary>25000?(firstName+' '+lastName):null}
//The gives [null,null,Kim Terry,Mary Jin,James Sally]

The problem with collect is that the size of transformed list is equal to the original list even if the transformed element is null. So we need to have an additional
step to get non-null elements from the transformed list.

Instead of this, we can simply use findResults in following way:

println Employee.list().findResults{it.salary>25000?(firstName+' '+lastName):null}
//This gives a list of size equal to total non-null elements(3 in this case) : [Kim Terry,Mary Jin,James Sally].

Further if we want to get just the first non-null element after transformation, we can use findResult instead of findResults.

println Employee.list().findResult{it.salary>25000?(firstName+' '+lastName):null}
//This gives "Kim Terry".

I found it very useful.

Hope it heps you too,:)

Vivek Sachdeva

FOUND THIS USEFUL? SHARE IT

comments (3)

  1. André Buzzo

    Is it better than executeQuery? I know that executeQuery searchs directly through the database, hence faster, so what is the benefit in using this approach?

    Reply
    1. vivek.sachdeva

      Hi André,

      As you mentioned, executeQuery is used to search through the database. But findResult and findResults methods are used on Collections. In this example, Employee.list() returns a list and these methods are applied to it.

      Reply

Leave a comment -