有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我有列表<RecipeDto>食谱。我只想使用stream从RecipeDto类中获取关键字ingredients。此代码工作不正常

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

共 (2) 个答案

  1. # 1 楼答案

    如果您想要成分关键字的列表,只需执行以下操作:

    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
    
  2. # 2 楼答案

    如果您真的要将成分关键字流(如变量名称所示)收集成一个映射为小写的流,您可以concat它们如下:

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

    此外,如果您想将其收集到List<String>作为:

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