英文:
How can I convert a for loop into Stream and break it in the middle?
问题
如何将以下代码片段转换为流格式?尝试了filter、foreach和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
操作。如果 status
是 INVALID
或者 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);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论