0

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);
Jack
  • 1
  • 21
  • 118
  • 236
  • 3
    Return `ri` from `map()` and then `.collect(Collectors.toList())`. – shmosel Dec 01 '22 at 23:09
  • The code would look nice if you would extract the logic from the `map` into a separate method. Also, if you're using Java 16+ instead of `collect(Collectors.toList())` you can use terminal operation `toList()`. – Alexander Ivanchenko Dec 01 '22 at 23:16
  • Thanks a lot for both of you. Alexander, what do you mean with separate methods? Could you post an example pls? – Jack Dec 01 '22 at 23:30

0 Answers0