java - 在循环中使用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
解决方案
如果您希望将循环中的所有内容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
}
推荐阅读
- kubernetes - 使用 JSONPATH 获取 configmap 值
- c - B 树算法,返回小于一个值的所有键
- python - Pywin32 和 Office365
- swiftui - SwiftUI:测试应用程序时清除当前用户身份验证 uid
- html - 如何使用 css-grid 覆盖圆形和半圆形元素以进行响应式设计
- python - 检查大数据框空值的总和
- r - 如何分配值并传输到长格式数据
- spring-boot - Neo4j Spring Boot Actuator 健康和不支持的身份验证令牌,仅当禁用身份验证时才允许方案“无”
- javascript - 将 @availity 与 react-scripts 一起使用:“当前未启用对实验性语法 'jsx' 的支持”
- java - 关于将 Slack webhook 添加到 Java Util 文件的建议