Monday, 14 January 2019

Groovy: Spread Operator Vs Iterable interface


You can apply Spread (*.) operator on any class that implements the Iterable interface.

HelloWorld.groovy
class Employee{
 String firstName
 String lastName
}

class CompositeObject implements Iterable<Employee> {
    def employees = [
  new Employee (firstName : "Menon", lastName : "Hari"),
  new Employee (firstName : "Bhat", lastName : "Srini"),
  new Employee (firstName : "Krishna", lastName : "Gurram")
 ]

    @Override
    Iterator<Employee> iterator() {
        employees.iterator()
    }
}

CompositeObject compositeObj = new CompositeObject()

def firsNames = compositeObj*.firstName
def lastNames = compositeObj*.lastName

println "firstNames : ${firsNames}"
println "lastNames : ${lastNames}"


Output

firstNames : [Menon, Bhat, Krishna]
lastNames : [Hari, Srini, Gurram]

If you would like to know, how to write custom iterator in Java, I would recommend you to go through my below post.




Previous                                                 Next                                                 Home

No comments:

Post a Comment