Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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());
like image 574
Lily Avatar asked Dec 15 '25 05:12

Lily


1 Answers

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
like image 196
Dani Mesejo Avatar answered Dec 16 '25 21:12

Dani Mesejo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!