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

user1888955 :

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;
}
Mureinik :

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);
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=403742&siteId=1