使用闭包在Groovy中检查列表成员的字段是否为null

时间:2013-10-10 16:47:51

标签: java groovy null

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

有什么想法吗?提前谢谢!

2 个答案:

答案 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
}