How to collect data inside Java Stream from external service?

Viewed 119

I have such Java 7 code

List<String> foodPreferencesStr = ... populating this list

EdamamRequestModel params = new EdamamRequestModel();
List<EdamamRecipeModel> recipesList = new ArrayList<EdamamRecipeModel>();

for(String pref : foodPreferencesStr) {
    params.setQ(pref);
    params.setFrom(fromInt);
    params.setTo(toInt);
    recipesList.addAll(edamamService.searchRecipe(params));
}

How to make it Java 8 with Stream API?

I tried to make it like this

List<EdamamRecipeModel> recipesList = foodPreferencesStr.stream()
        .map(pref -> {
            params.setQ(pref);
            params.setFrom(fromInt);
            params.setTo(toInt);

            return params;
        }).collect(...);

but do not understand how to call edamamService.searchRecipe(params) inside Stream API and add all its result to List<EdamamRecipeModel> recipesList

Please advice.

1 Answers
List<EdamamRecipeModel> recipesList = foodPreferencesStr.stream()
        .map(pref -> {
            EdamamRequestModel params = new EdamamRequestModel();

            params.setQ(pref);
            params.setFrom(fromInt);
            params.setTo(toInt);

            return params;
        })
        .map(params -> edamamService.searchRecipe(params))
        .flatMap(List::stream)
        .collect(Collector.toList());
Related