Users Pricing

forum

Home Forums Use streams for terminating loop over collection conditionally – MindStick

Use streams for terminating loop over collection conditionally

marcel ethan 1508 20 Dec 2015
How to use streams to achieve something like what the following code snippet shows ? Basically, I need to terminate a loop returning one value based on a condition, or returning another value again, based on a condition.

enum Day {
  SUNDAY, MONDAY, TUESDAY, WEDNESDAY

class MyObj {
  Day d;
  public Day getDay();
}
List<MyObj> myObjList;
Day Myfunc () {
// If atleast one obj belongs to SUNDAY or MONDAY, return.
Day myDay = null;
for(MyObj myObj : myObjList) {
  if(myObj.getDay() == Day.SUNDAY || myObj.getDay() == Day.MONDAY) {
    return myObj.getDay();
  }
  else if (myObj.getDay() == Day.TUESDAY) {
    myDay = myObj.getDay();
  }
 }
return myDay;
}

1 Answers

Anonymous User 21 Dec 2015 Accepted Answer
Markdown for AI

A clean, structured version of this page for AI assistants and LLMs.

Open .md