使用java8重构多个或条件

时间:2018-02-06 02:12:44

标签: java-8

我有一个方案可以使用java8

重构if块中的多个或条件
private boolean isStatusAvailable(List<Hierarchy> hierarchyList, String status, int i) {
    return isContainsStatus(hierarchyList.get(i+1), status) || isContainsStatus(hierarchyList.get(i+1), ResultStatus.SUCCESS) || isContainsStatus(hierarchyList.get(i+1), ResultStatus.PEND);
}
private boolean isContains(Hierarchy hierarchy, String status) {
    return hierarchy.getStatus().contains(status);
}
public enum ResultStatus {
    SUCCESS,
    SUCCESS_PENDING,
    SUCCESS_SUMMARY,
    PEND
}

有没有办法在java8中重构上面的代码?

1 个答案:

答案 0 :(得分:4)

总是有可能引入一个循环:

private boolean isStatusAvailable(List<Hierarchy> hierarchyList, ResultStatus status, int i) {
  Hierarchy hierarchy = hierarchyList.get(i + 1);
  for (ResultStatus s : Arrays.asList(status, SUCCESS, PEND)) {
    if (isContainsStatus(hierarchy, s)) {
      return true;
    }
  }
  return false;
}

如果您想使用Stream,那么您可以写:

private boolean isStatusAvailable(List<Hierarchy> hierarchyList, ResultStatus status, int i) {
  Hierarchy hierarchy = hierarchyList.get(i + 1);
  return Stream.of(status, SUCCESS, PEND).anyMatch(s -> isContainsStatus(hierarchy, s));
}