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
闭包)我是如何遍历每个widget
个fizzes
元素并检查boron
字段是否为空?
例如,在Java中,我可能会写:
Widget widget = new Widget();
for(Fizz fizz : widget.getFizzes())
if(fizz.getBoron() == null)
// ... process somehow
有什么想法吗?提前谢谢!
答案 0 :(得分:1)
findAll
'他们,他们循环结果:
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 }
<强>更新强>
要检查没有boron
为空,请使用every
:
def everyBoronNotNull = w.fizzes.every { it.boron != null }
assert !everyBoronNotNull
答案 1 :(得分:0)
在groovy中执行此操作的一个好方法是首先使用findAll
过滤列表。例如:
widget.fizzes.findAll { it.boron != null }.each { fizz ->
// do something with each fizz with non-null boron
}