java - 如何使用 JAVA8 流从类中获取所需的值

标签 java java-8 java-stream

我有列表<RecipeDto>食谱。我只想使用流从 RecipeDto 类中获取 keywordsingredeients。此代码无法正常工作。

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/

相关文章:

java - .Net 可以加载 IL 文件(例如 java 类文件),还是必须加载整个程序集?

java - 如何解决UnsupportedOperationException : Can't convert to dimension: type=0x12

java - 获取表示异常来源的 Method 对象

java - 编译错误 : Cannot us a method returning CompetionStage as a Handler for requests

java - 在抽象类和子方法之间使用Spring事务代理

java - 为什么 String 方法regionMatches 不委托(delegate)给重载方法

java - 使用 groupingBy 的类属性的平面映射收集器

java - 如何使用 Java 流将多个列表转换为单个列表?

lambda - [SonarLint] : make this anonymous inner class a lambda

java - 深入比较数组中的每个元素