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


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

最佳答案

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 }




更新:

要检查是否没有boron为空,请使用every

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

assert !everyBoronNotNull

10-05 23:48