1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| class Book { String name List authors } class Author { String name Address addr } class Address { String province String city }
def addr1 = new Address(province:'Guangdong',city:'Shenzhen') def addr2 = new Address(province:'Gunagdong',city:'Guangzhou') def addr3 = new Address(province:'Hunan',city:'Changsha') def addr4 = new Address(province:'Hubei',city:'Wuhan') def books = [new Book(name:'A glance at Java',authors:[new Author(name:'Tom',addr:addr1)]), new Book(name:'Deep into Groovy',authors:[new Author(name:'Tom',addr:addr1),new Author(name:'Mike',addr:addr3)]), new Book(name:'A compare of Struts and Grails',authors:[new Author(name:'Wallace',addr:addr4),new Author(name:'Bill',addr:addr2)]), new Book(name:'learning from Groovy to Grails',authors:[new Author(name:'Wallace',addr:addr3)])]
def booksOfTomOldWay = [] books.each { def book = it def aus = it.authors aus.each { au-> if (au.name == 'Tom') booksOfTomOldWay << book.name } }
println booksOfTomOldWay
def booksOfTom = books.grep{ it.authors.any{ it.name == 'Tom' } }.name
println booksOfTom
|