Groovy Applied: findAll

Posted by Chad | Posted in Groovy | Posted on 18-12-2009

1

Use findAll to match items in separate lists.

Problem: Given a list of employee names and a list of employee objects, find the id of each employee whose name is in the list.

Provided:

def namesList = ["Joe","Jane"]
class Student {def name; def id}
def students = [
    new Student([name:"Joe",id:101]),
    new Student([name:"Fred",id:102]),
    new Student([name:"Jane",id:104])
    ]


Solution:

students.findAll {
    namesList.contains(it.name)
}.id


Output:

[101,104]



Share:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DZone
  • FriendFeed
  • Ping.fm
  • StumbleUpon
  • Technorati

Comments posted (1)

I love groovy. 2 things I love doing in groovy: XML and Collections.
I really like using list.any{} in tests.
assert list.any{it.name == “James”}

Write a comment

What is 14 + 2 ?
Please leave these two fields as-is:
IMPORTANT! To be able to proceed, you need to solve the following simple math (so we know that you are a human) :-)