1

Probably not the best title, but I'll explain:
I have an array of objects - lets call them Person.
Each Person has a Name. I want to create an array of Name respectively.

Currently I have:

def peopleNames = new ArrayList<String>()

for (person in people)
{
    peopleNames.add(person.name)
}

Does groovy provide a better means of doing so?

4 Answers 4

8

Groovy provides a collect method on Groovy collections that makes it possible to do this in one line:

def peopleNames = people.collect { it.name }
Sign up to request clarification or add additional context in comments.

1 Comment

Both methods are good - I chose this as it is a bit more clear and most people maintaining this code are not proficient with groovy as it is "only a testing tool"
6

Or the spread operator:

def peopleNames = people*.name

1 Comment

I always forget about that... Cool!
3

The most concise way of doing this is to use a GPath expression

// Create a class and use it to setup some test data
class Person {

  String name
  Integer age
}

def people = [new Person(name: 'bob'), new Person(name: 'bill')]

// This is where we get the array of names
def peopleNames = people.name

// Check that it worked
assert ['bob', 'bill'] == peopleNames

This is one whole character shorter than the spread operator suggestion. However, IMO both the sperad operator and collect{} solutions are more readable, particularly to Java programmers.

Comments

1

Why don't you try this? I like this one because it's so understandable

def people = getPeople() //Method where you get all the people
def names = []
people.each{ person ->
   names << person.name
}

4 Comments

I can't see that this is better than using collect. With this method, you need to have a separate line creating the names list, and then manipulate the list from inside the loop. collect keeps all this together inside a single block.
Totally not readable for a java developer that never laid eyes on groovy code (myself including). Does this sample use "fixtures"? (I heard the term but don't have any idea what it is)
@Ron No, it uses the left shift operator
It's not better, but more understandable than the collect operator and more readable for a java developer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.