How to use threads to complete a loop to collect conditionally

How to use threads to achieve something like what the following code snippet shows? Basically, I need to end 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;
}
+4
source share
2 answers

I understand the logic of your function as follows:

  • If there is a SUNDAY or MONDAY at the entrance, return the first one.
  • Otherwise, if TUESDAY, return it.
  • Otherwise, returns null.

You can implement this logic in Java-8 style by repeating the list twice and using Optional.orElseGet:

myObjList.stream().map(MyObj::getDay).filter(d -> d == Day.SUNDAY || d == Day.MONDAY)
    .findFirst()
    .orElseGet(() -> myObjList
        .stream().map(MyObj::getDay).anyMatch(d -> d == Day.TUESDAY) ? Day.TUESDAY : null);

, .


:

int priority(Day d) {
    switch(d) {
    case SUNDAY:
    case MONDAY:
        return 10; // max priority
    case TUESDAY:
        return 5;
    default:
        return 0;
    }
}

Stream.max:

return myObjList.stream().map(MyObj::getDay).max(Comparator.comparingInt(this::priority))
        .filter(day -> priority(day) > 0).orElse(null);

, , , : , priority.

+5

:

list.stream().filter(myObj -> myObj.getDay() == Day.SUNDAY || myObj.getDay() == Day.MONDAY);

return .

0

Source: https://habr.com/ru/post/1621058/


All Articles