开发者

Creating an array of properties of items in an existing array

Probably not the best ti开发者_StackOverflowtle, 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?


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

def peopleNames = people.collect { it.name }


Or the spread operator:

def peopleNames = people*.name


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.


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
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜