首页 > 解决方案 > 在循环中使用java“for each”和“continue”

问题描述

我有一个看起来像这样的大方法:

for (Person person : persons) {
   if (!person.isValid()) {
      continue;
   }
   ....
   boolean isDeleted = deletePersonFromDB1(person);
   if (!isDeleted) {
     continue;
   }
   ....

}

基本上我想从不同的数据库源中删除人员列表。如果任何操作失败,我想继续下一个人。我想像这样简化并将我的业务逻辑放在一个方法中:

for (Person person : persons) {
    checkValidityAndDelete(person)
}

但不幸的是,我不能continue在我的方法中使用这个词checkValidityAndDelete

标签: javaloops

解决方案


如果您希望将循环中的所有内容return拉出到另一个方法中,另一个选择是简单地从它中调用以触发该方法停止。

public void checkValidity(final Person person) {
    if (person.something) {
        return;
        // From the calling loop, this will act as a continue
        // since the method call would stop, and so the next
        // loop iteration would start.
    }
    // Do some more stuff
}

推荐阅读