Sunday, 27 January 2019

Groovy: map: every: Check whether all the elements satisfy given criteria or not


public boolean every(Closure predicate)
This method returns true, if all the elements in the map satisfies given criteria, else false.

Example
result1 = employees1.every{id, employee -> employee.age > 18}

Find the below working application.

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.every{id, employee -> employee.age > 18}
result2 = employees2.every{id, employee -> employee.age > 18}

println "is all the employees age in employees1 > 18 : $result1"
println "is all the employees age in employees2 > 18 : $result2"

Output
is all the employees age in employees1 > 18 : false
is all the employees age in employees2 > 18 : true


Previous                                                 Next                                                 Home

No comments:

Post a Comment