How to get the required values from a class using JAVA8 stream

Lily :

I have List<RecipeDto> recipes. I want to get only the keywords and ingredeients from RecipeDto class using stream. This code is not working fine.

List<String> keywordsAndIngredientsStream = 
recipes.stream().forEach(recipeDto -> {
            recipeDto.getIngredients().forEach(ingredient -> ingredient.toLowerCase());
            recipeDto.getKeywords().forEach(keywords -> keywords.toLowerCase());})
           .collect(Collectors.toList());
Dani Mesejo :

If you want a list of the ingredients and keywords, just do:

ArrayList<RecipeDTO> recipes = new ArrayList<RecipeDTO>() {{

    add(new RecipeDTO(Arrays.asList("onion", "rice"), Arrays.asList("yummy", "spicy")));
    add(new RecipeDTO(Arrays.asList("garlic", "tomato"), Arrays.asList("juicy", "salty")));

}};

List<String> ingredientsAndKeywords = recipes.stream()
        .flatMap(recipe -> Stream.concat(recipe.getIngredients().stream(), recipe.getKeywords().stream()))
        .map(String::toLowerCase)
        .collect(toList());

for (String ingredientsAndKeyword : ingredientsAndKeywords) {
    System.out.println(ingredientsAndKeyword);
}

Output

onion
rice
yummy
spicy
garlic
tomato
juicy
salty

Update

Given the new requirements, just do:

List<String> ingredientsAndKeywords = recipes.stream()
                .map(recipe -> Stream.concat(recipe.getIngredients().stream(), recipe.getKeywords().stream())
                        .map(String::toLowerCase).collect(joining(" ")))
                .collect(toList());

        for (String ingredientsAndKeyword : ingredientsAndKeywords) {
            System.out.println(ingredientsAndKeyword);
        }

Output

onion rice yummy spicy
garlic tomato juicy salty

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=164143&siteId=1