0
public class Widget {
    private List<Fizz> fizzes;
    // ... lots of other fields
}

public class Fizz {
    private String boron;
    // ... lots of other fields
}

如果我有一个 的实例Widget,例如widget,如何(在 Groovy 中,使用each闭包)循环遍历每个widgetfizzes元素并检查该boron字段是否为空?

例如,在 Java 中,我可能会这样写:

Widget widget = new Widget();
for(Fizz fizz : widget.getFizzes())
    if(fizz.getBoron() == null)
        // ... process somehow

有任何想法吗?提前致谢!

4

2 回答 2

1

findAll'em,然后他们循环遍历结果:

class Widget {
  List<Fizz> fizzes
}

class Fizz {
  String boron
}

w = new Widget(
  fizzes: [
    new Fizz(boron: 'boron 1'),
    new Fizz(boron: 'boron 2'),
    new Fizz()
  ]
)

nullFizzes = w.fizzes.findAll { it.boron == null }

assert nullFizzes.size() == 1

nullFizzes.each { println it }

更新:

要检查 noboron是否为空,请使用every

def everyBoronNotNull = w.fizzes.every { it.boron != null }

assert !everyBoronNotNull
于 2013-10-10T16:59:16.783 回答
0

在 groovy 中执行此操作的一个好方法是先使用findAll. 例如:

widget.fizzes.findAll { it.boron != null }.each { fizz ->
    // do something with each fizz with non-null boron
}
于 2013-10-10T16:59:15.987 回答