如何从Groovy中的对象字段中提取新列表

Rei*_*eus 16 groovy

在Groovy中,如何从以下内容中提取新列表:

   def people = [ 
           new Person(name:"Tom", yearOfBirth:1985),
           new Person(name:"Abigail", yearOfBirth:1987),
           new Person(name:"Joyce", yearOfBirth:1984),
           new Person(name:"James", yearOfBirth:1987),
           new Person(name:"Scott", yearOfBirth:1985),
           new Person(name:"Ruth", yearOfBirth:1984)
       ]  

   class Person {
       String name
       int yearOfBirth
   }
Run Code Online (Sandbox Code Playgroud)

所以新列表看起来像这样:

 ["Tom", "Abigail", "Joyce", "James", "Scott", "Ruth"]    
Run Code Online (Sandbox Code Playgroud)

tim*_*tes 24

你可以做:

def names = people.name
Run Code Online (Sandbox Code Playgroud)

  • 你需要像'people.collect {it.name =='Tom'?'蒂姆':it.name}` (5认同)
  • @tim_yates嗯,在这种情况下,我觉得两种语法都没问题,因为这是一个非常简单的例子.但总的来说,我更喜欢`*.prop`,因为我觉得它的含义更明显; 它_always_表示`.collect {it.prop}`.`people.name`选项在`people`对象(一个`propertyMissing`实现,它没有`name`属性)上依赖于相当多的魔法,我最好每次看到它都不想记住表达:) (5认同)