user1888955:
¿Cómo puedo convertir el siguiente fragmento de código en formato de flujo, filtro tratado, foreach y el mapa, pero todavía algo anda mal.
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:
Vamos a descomponerlo bucle. En primer lugar, se pasa de todos los validadores y llamada validate
- que es una map
operación. Si el status
es INVALID
o VALID
, lo devuelva - que es una filter
operación con findFirst
la lógica. Y si usted no puede encontrar uno, que regrese UNKNOWN
- que es una orElse
operación. Poniendolo todo junto:
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);
}