forum

Home / DeveloperSection / Forums / Use streams for terminating loop over collection conditionally

Use streams for terminating loop over collection conditionally

marcel ethan 1200 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;
}

Updated on 21-Dec-2015

Can you answer this question?


Answer

1 Answers

Liked By