public Object
find(Closure closure)
This method finds and return the first value that matches
to given closure. This method returns null, if nothing is matched to the closre
criteria.
Example
result = employees.find {it.key == 3}
result = employees.find {it.value.name == 'Krishna'}
HelloWorld.groovy
class Employee{ String name int age int id public Employee(int id, int age, String name){ this.id = id this.age = age this.name = name } String toString(){ return "id : ${this.id}, age : ${this.age}, name : ${this.name}" } } Employee emp1 = new Employee(1, 32, 'Sunil') Employee emp2 = new Employee(2, 29, 'Krishna') Employee emp3 = new Employee(3, 41, 'Gopi') Employee emp4 = new Employee(4, 35, 'krishna') employees = [ 1 : emp1, 2 : emp2, 3 : emp3, 4 : emp4 ] println "Get an employee with id 3" def result = employees.find {it.key == 3} println "${result.value}" println "\nGet an employee with name 'Krishna'" result = employees.find {it.value.name == 'Krishna'} println "${result.value}"
Output
Get an employee with id 3
id : 3, age : 41, name : Gopi
Get an employee with name 'Krishna'
id : 2, age : 29, name : Krishna
No comments:
Post a Comment