Lily
Lily

Reputation: 707

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());

Upvotes: 3

Views: 175

Answers (2)

Dani Mesejo
Dani Mesejo

Reputation: 61920

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

Upvotes: 2

Naman
Naman

Reputation: 32028

If you were to really collect the ingredients and keywords stream (as the variable name suggests) into one with the mapping to lowercase, you could concat them as:

Stream<String> keywordsAndIngredientsStream = recipes.stream()
        .flatMap(rec -> Stream.concat(rec.getIngredients().stream(), rec.getKeywords().stream())
                .map(String::toLowerCase));

and further, if you wanted to collect it to a List<String> as:

List<String> keywordsAndIngredientsList = keywordsAndIngredientsStream.collect(Collectors.toList());

Upvotes: 2

Related Questions