如何将for循环转换为流(Stream),并在中途中断?

huangapple go评论74阅读模式
英文:

How can I convert a for loop into Stream and break it in the middle?

问题

如何将以下代码片段转换为流格式尝试了filterforeach和map但仍然有些问题

```java
private Status validate(final Type type, final String id) {
    for(Validator validator : validators) {
        Status status = validator.validate(type, id);

        if (status == Status.INVALID || status == Status.VALID) {
            return status;
        }
    }

    return Status.UNKNOWN;
}
英文:

How can I convert the following piece of code into stream format, tried filter, foreach and map but still something is wrong.

private Status validate(final Type type, final String id) {
    for(Validator validator : validators) {
        Status status = validator.validate(type, id);

        if (status == Status.INVALID || status == Status.VALID) {
            return status;
        }
    }

    return Status.UNKNOWN;
}

答案1

得分: 3

让我们来分解这个循环。首先,您会遍历所有的验证器并调用 validate 函数 - 这是一个 map 操作。如果 statusINVALID 或者 VALID,您会返回它 - 这是一个带有 findFirst 逻辑的 filter 操作。如果您找不到任何一个符合条件的,您会返回 UNKNOWN - 这是一个 orElse 操作。将所有这些放在一起:

private Status validate(final Type type, final String id) {
    return validators.stream()
                     .map(v -> v.validate(type, id))
                     .filter(s -> s == Status.INVALID || s == Status.VALID)
                     .findFirst()
                     .orElse(Status.UNKNOWN);
}
英文:

Let's break this loop down. You first go over all the validators and call validate - that's a map operation. If the status is INVALID or VALID, you return it - that's a filter operation with findFirst logic. And if you can't find one, you return UNKNOWN - that's an orElse operation. Putting it all together:

private Status validate(final Type type, final String id) {
    return validators.stream()
                     .map(v -> v.validate(type, id))
                     .filter(s -> s == Status.INVALID || s == Status.VALID)
                     .findFirst()
                     .orElse(Status.UNKNOWN);
}

huangapple
  • 本文由 发表于 2020年4月4日 04:51:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/61020220.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定