Sunday, 27 January 2019

Groovy: Map: findAll: Find all the elements that matches to given criteria


public Collection findAll(Closure closure)
Find all the elements that matches to given criteria.

Example
Below statement gets all the female employee details.
result = employees.findAll {it.value.gender == 'F'}

Below statement gets all the male employee details.
result = employees.findAll {it.value.gender == 'M'}

HelloWorld.groovy
class Employee{
 String name
 int age
 int id
 char gender
 
 public Employee(int id, int age, String name, char gender){
  this.id = id
  this.age = age
  this.name = name
  this.gender = gender
 }
 
 String toString(){
  return "<id : ${this.id}, age : ${this.age}, name : ${this.name}, gender : ${this.gender}>"
 }
}

Employee emp1 = new Employee(1, 32, 'Susmitha', 'F' as char)
Employee emp2 = new Employee(2, 29, 'Krishna', 'M' as char)
Employee emp3 = new Employee(3, 41, 'Gopika', 'F' as char)
Employee emp4 = new Employee(4, 35, 'krishna', 'M' as char)

employees = [
 1 : emp1,
 2 : emp2,
 3 : emp3,
 4 : emp4
]

println "Get all the female employees"
def result = employees.findAll {it.value.gender == 'F'}
println "${result}"

println "\nGet all the male employees"
result = employees.findAll {it.value.gender == 'M'}
println "${result}"

Output
Get all the female employees
[1:<id : 1, age : 32, name : Susmitha, gender : F>, 3:<id : 3, age : 41, name : Gopika, gender : F>]

Get all the male employees
[2:<id : 2, age : 29, name : Krishna, gender : M>, 4:<id : 4, age : 35, name : krishna, gender : M>]


Previous                                                 Next                                                 Home

No comments:

Post a Comment