I would like to convert below code with Java's 8 Stream. I'm new to streams. Please help to improve this code.
List<ValidationErrorResult> errors = new ArrayList<>();
for(String stageKey : stage.getParentStages()){
// get stage from db
Stage dbStage = stageService.getStageByKey(stageKey);
//comparing enum
if(!StageType.DEV.name().equals(dbStage.getType().name())){
errors.add(ValidationErrorResult.builder().validationError(StageValidationError.DEV_STAGE_VALIDATION).build());
} else if(!StageType.TEST.name().equals(dbStage.getType().name())){
errors.add(ValidationErrorResult.builder().validationError(StageValidationError.TEST_STAGE_PARENT_ENV_VALIDATION).build());
}
}
return errors;
Thanks
Firstly, convert your list to stream with stream()
. Then, with map()
method, you can create new stream with others type.
At the end, I used Collectors.toList()
to convert it as basic list, and "end" the stream.
return stage.getParentStages().stream().map(stageService::getStageByKey).map((dbStage) -> {
if(!StageType.DEV.name().equals(dbStage.getType().name())){
return ValidationErrorResult.builder().validationError(StageValidationError.DEV_STAGE_VALIDATION).build());
} else if(!StageType.TEST.name().equals(dbStage.getType().name())){
return ValidationErrorResult.builder().validationError(StageValidationError.TEST_STAGE_PARENT_ENV_VALIDATION).build());
}
return null;
}).collect(Collectors.toList());
Just, such as I didn't know what you would like to do when you don't add something in errors list, it return null.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.