In my Spring Boot app, I am trying to return a list of RecipeIngredient
as shown below. In this example, I am iterating on request.getRecipeIngredients()
and at first fing ingredient and its unit.
Then, I create a RecipeIngredient and set its fields. But after this stage, I need to create a list and return it for using in recipeIngredientRepository.saveAll()
method. I can also save ri after each iteration, but I am not sure if one of these approaches is ok.
So, how should achieve this using a proper approach with Java Stream?
List<RecipeIngredient> list = request.getRecipeIngredients().stream()
.map(recipeIngredient -> {
final Ingredient ingredient = ingredientRepo
.findById(recipeIngredient.getIngredientId())
.orElseThrow(() -> new NoSuchElementFoundException(NOT_FOUND));
final Unit unit = unitRepo.findById(recipeIngredient.getUnitId())
.orElseThrow(() -> new NoSuchElementFoundException(NOT_FOUND));
RecipeIngredient ri = new RecipeIngredient();
ri.setRecipe(recipe);
ri.setIngredient(ingredient);
ri.setUnit(unit);
ri.setAmount(recipeIngredient.getAmount());
// return list of ri ???
});
recipeIngredientRepo.saveAll(list);