Reputation: 23
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
?
Upvotes: 2
Views: 459
Reputation: 1267
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
});
Upvotes: 0
Reputation: 1837
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
Upvotes: 2
Reputation: 1145
this way you can apply for-each loop.
for (Summary summary: smryList) {
if (Number.equals(summary.getNumber())) {
NumberPresent = true;
break;
}
// ...
}
Upvotes: 5