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);
};
}
//想象所有字段的获取器和设置器。
public class Menuplan {
private Meal breakfast;
private Meal lunch;
private Meal dinner;
private Recipe snack;
}
public class Meal {
private Recipe recipe;
private Reicpe snack;
}
如果Menuplan已经分配了给定的食谱(作为小吃或食谱),我可以通过上述方法进行测试。
我想知道是否有更优雅/更短的方法来编写函数。
答案 0 :(得分:4)
一种在一个流中完成全部工作的解决方案是
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));
}
三个流元素this.breakfast, this.lunch, this.dinner
得到调用meal.getRecipe()
和meal.getSnack()
的相同处理以形成一个新流,该流与仅持有this.snack
的单个元素流连接
anyMatch
将在发现满足条件的元素后立即返回true
。否则,它将返回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));
}
另一种选择是
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));
}
答案 1 :(得分:1)
您可能应该避免流
private boolean hasDuplicates(Recipe recipe) {
for (Meal each : Arrays.asList(breakfast, lunch, dinner)) {
if (each.getRecipe().equals(recipe) || each.getSnack().equals(recipe) {
return true;
}
}
return snack.equals(recipe);
}