在提取的实体列表中查找重复项

ale*_*der 1 java java-8

private boolean hasDuplicates(Recipe recipe) {
    List<Recipe> currentRecipes = new ArrayList<>();

    Stream.of(this.breakfast, this.lunch, this.dinner).forEach(meal -> {
        currentRecipes.add(meal.getRecipe());
        currentRecipes.add(meal.getSnack());
    });
    currentRecipes.add(this.snack);

    return currentRecipes.contains(recipe);
    };

}
Run Code Online (Sandbox Code Playgroud)

// 想象一下所有字段的 getter 和 setter。

public class Menuplan {
  private Meal breakfast;
  private Meal lunch;
  private Meal dinner;
  private Recipe snack;
}

public class Meal {
  private Recipe recipe;
  private Reicpe snack;
}
Run Code Online (Sandbox Code Playgroud)

如果 Menuplan 已经分配了给定的食谱(作为零食或食谱),我使用上述方法进行测试。

我想知道是否有更优雅/更短的方法来编写函数。

Hol*_*ger 5

在一个流中完成所有操作的解决方案是

private boolean hasDuplicates(Recipe recipe) {
    return Stream.concat(
        Stream.of(this.breakfast, this.lunch, this.dinner)
            .flatMap(meal -> Stream.of(meal.getRecipe(), meal.getSnack())),
        Stream.of(this.snack))
   .anyMatch(Predicate.isEqual(recipe));
}
Run Code Online (Sandbox Code Playgroud)

三个流元素this.breakfast, this.lunch, this.dinner得到相同的调用处理meal.getRecipe()meal.getSnack()形成一个新流,该流与仅持有 的单个元素流连接this.snack

anyMatchtrue一旦找到满足条件的元素,就会返回。否则,它将返回false

您可以考虑将不符合其他元素通用模式的一个元素移出 Stream 操作:

private boolean hasDuplicates(Recipe recipe) {
    return this.snack.equals(recipe) ||
        Stream.of(this.breakfast, this.lunch, this.dinner)
            .flatMap(meal -> Stream.of(meal.getRecipe(), meal.getSnack())
            .anyMatch(Predicate.isEqual(recipe));
}
Run Code Online (Sandbox Code Playgroud)

另一种选择是

private boolean hasDuplicates(Recipe recipe) {
    return this.snack.equals(recipe) ||
        Stream.of(this.breakfast, this.lunch, this.dinner)
            .anyMatch(meal -> meal.getRecipe().equals(recipe)
                           || meal.getSnack().equals(recipe));
}
Run Code Online (Sandbox Code Playgroud)