我有列表<RecipeDto>
食谱。我只想使用流从 RecipeDto 类中获取 keywords 和 ingredeients。此代码无法正常工作。
List<String> keywordsAndIngredientsStream =
recipes.stream().forEach(recipeDto -> {
recipeDto.getIngredients().forEach(ingredient -> ingredient.toLowerCase());
recipeDto.getKeywords().forEach(keywords -> keywords.toLowerCase());})
.collect(Collectors.toList());
最佳答案
如果您想要成分和关键字的列表,只需执行以下操作:
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);
}
输出
onion
rice
yummy
spicy
garlic
tomato
juicy
salty
更新
鉴于新要求,只需执行:
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);
}
输出
onion rice yummy spicy
garlic tomato juicy salty
关于java - 如何使用 JAVA8 流从类中获取所需的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57997589/