考虑以下 POJO 类,请注意所有属性都可以为 null 并且不被
Optional
包裹
public class Food{
String name; // can be null
Double weight;
// gettes & setters & constructor
}
public class Drink{
String name; // can be null
Long volume;
// gettes & setters & constructor
}
public class Meal{
Long id;
Timetstamp date;
List<Food> foodList;
List<Drink> drinkList;
// getters & setters
// constructor
}
现在有 2 餐,我想找到独家食品和饮料
Meal lunch = new Meal();
Meal dinner = new Meal();
// .. skip logic to fill in attribute value for lunch & dinner
List<Food> uniqueFoodInLunchAndDinner = .... // require implementation
List<Drink> uniqueDrinkInLunchAndDinner = .... // require implementation
我的问题是如何使用更少的代码实现上述逻辑,同时又不牺牲性能。
Blow 是我的代码,但我认为它不够好
List<Food> getUniqueFoodInLunchAndDinner(Meal lunch, Meal dinner){
List<Food> missingFoodinDinner = lunch.getFood().stream.filter(Objects::nonNull).filter(foodInLunch -> {
dinner.getFood().stream()
.filter(Objects::nonNull)
.map(Food::getName)
.filter(Objects::nonNull)
.collect(Collectors.toList())
.contains(foodInLunch.getName()) == false).collect(Collectors.toList());
})
return dinner.getFood().addAll(missingFoodinDinner );
}
// same logic for drink...
我觉得你太主要了
filters
,不确定你是否真的需要它们。我认为您只需要foodInLunch.getName() == false
为什么不使用的物品
X.stream().map(Food::getName).collect(Collectors.toSet()).contains(foodInLunch.getName()) == false).collect(Collectors.toList());
我认为上面的代码片段应该返回相同的结果。您可以将
X
作为参数传递。第一种情况是食物,第二种情况是饮料