2

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?

4
  • 2
    I’m voting to close this question because this is clearly a homework assignment and you should show us what you have attempted first. Commented Oct 23, 2020 at 5:29
  • geeksforgeeks.org/for-each-loop-in-java Commented Oct 23, 2020 at 5:31
  • 1
    Yeah, looks like a homework problem. I suppose the first question for original poster is: "Tell me in once sentence what this code is doing." Commented Oct 23, 2020 at 5:33
  • @David Brossard : I know how to replace for loop with foreach, but my current functionality is having break statement too. I wanted to know how can we use break with foreach ? Commented Oct 23, 2020 at 5:36

3 Answers 3

5

this way you can apply for-each loop.

for (Summary summary: smryList) { if (Number.equals(summary.getNumber())) { NumberPresent = true; break; } // ... } 
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

0

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 }); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.