英文:
how to replace for loop by forEach
问题
String Number = "123";
boolean NumberPresent = false;
List<Summary> smryList = smryListResponse.getSummaryList();
for (Summary summary : smryList) {
if (Number.equals(summary.getNumber())) {
NumberPresent = true;
break;
}
}
if (NumberPresent) {
//perform some actions
}
英文:
My code is,
String Number = "123";
boolean NumberPresent = false;
List < Summary > smryList = smryListResponse.getSummaryList();
for (int i = 0; i < smryList.size(); i++) {
if (Number.equals(smryList.get(i).getNumber())) {
NumberPresent = true;
break;
}
}
if (NumberPresent) {
//perform some actions
}
How can I replace this complete for loop
functionality with forEach
?
答案1
得分: 5
for (Summary summary: smryList) {
if (Number.equals(summary.getNumber())) {
NumberPresent = true;
break;
}
// ...
}
英文:
this way you can apply for-each loop.
for (Summary summary: smryList) {
if (Number.equals(summary.getNumber())) {
NumberPresent = true;
break;
}
// ...
}
答案2
得分: 2
你不需要使用 for
或 forEach
来检测数字是否存在。你可以使用流以及 .anyMatch()
方法。例如:
String number = "123";
List<Summary> smryList = smryListResponse.getSummaryList();
boolean isNumberPresent = smryList
.stream()
.anyMatch(summary -> summary.getNumber().equals(number));
if (isNumberPresent) {
// ...
}
另外,你也可以尝试使用其他流方法,比如 .filter()
或其他方法。但我更倾向于使用 .anyMatch()
。
备注: 流和 Lambda 表达式仅适用于 Java 8 或更新版本。
否则,请使用已发布的 解决方案
英文:
You don't need to use for
or forEach
if you want to detect is number presented. You can use streams with i.e. .anyMatch()
method.
In example:
String number = "123";
List<Summary> smryList = smryListResponse.getSummaryList();
boolean isNumberPresent = smryList
.stream()
.anyMatch(summary -> summary.getNumber().equals(number));
if (isNumberPresent) {
// ...
}
Also, you can try do that with other stream methods, i.e. .filter()
or other. But I prefer to use .anyMatch()
.
>Remark: streams and lambda expressions works only with Java 8 or later.
>Otherwise use already posted solution
答案3
得分: 0
你可以用这个循环替换for循环。
for (Summary summary : smryList) {
if (Number.equals(summary.getNumber())) {
NumberPresent = true;
break;
}
}
另外,你可以尝试使用以下方式:
smryList.forEach(summary -> {// 在这里编写代码
});
英文:
you can replace the for loop with this loop.
for (Summary summary : smryList) {
if (Number.equals(summary.getNumber())) {
NumberPresent = true;
break;
}
}
otherwise, you can try
smryList.forEach(summary -> {//code here
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论