Users Pricing

forum

home / developersection / forums / use streams for terminating loop over collection conditionally

Use streams for terminating loop over collection conditionally

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

marcel ethan

Other


1 Answers

Anonymous User 21 Dec 2015 Accepted Answer