Sunday, 27 January 2019

Groovy: map: any: check whether any entry matches to the predicate


public boolean any(Closure predicate)
Return true, if any of the object satisfies given predicate, else false.

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, 17, 'Gopika', 'F' as char)
Employee emp4 = new Employee(4, 35, 'krishna', 'M' as char)

employees1 = [
 1 : emp1,
 2 : emp2,
 3 : emp3,
]

employees2 = [
 1 : emp1,
 2 : emp2,
 4 : emp4,
]

result1 = employees1.any{id, employee -> employee.age < 18}
result2 = employees2.any{id, employee -> employee.age < 18}

println "is any person in employees1 with age < 18 : $result1"
println "is any person in employees2 with age < 18 : $result2"

Output
is any person in employees1 with age < 18 : true
is any person in employees2 with age < 18 : false


Previous                                                 Next                                                 Home

No comments:

Post a Comment