kac*_*230 3 java java-8 java-stream
我只是试着理解Java中的流,并且我坚持排序阶段.我的目的是用一条流来获得最昂贵的蔬菜披萨.在这一点上,我得到披萨价格,但我无法对它进行排序.谁能告诉我应该怎么做呢?
我尝试这个:
pizzas.stream()
.flatMap(pizza -> Stream.of(pizza.getIngredients())
.filter(list -> list.stream().noneMatch(Ingredient::isMeat))
.map(list -> list.stream().map(Ingredient::getPrice).reduce(0,(a, b) -> a + b))
.sorted((o1, o2) -> o1.intValue() - o2.intValue())
)
.forEach(System.out::println);
Run Code Online (Sandbox Code Playgroud)
此代码返回未分类的比萨饼值.
import java.util.Collection;
import java.util.Comparator;
interface Pizza {
interface Ingredient {
boolean isMeat();
int getPrice();
}
Collection<Ingredient> getIngredients();
static boolean isVegetarian(Pizza pizza) {
return pizza.getIngredients().stream().noneMatch(Ingredient::isMeat);
}
static int price(Pizza pizza) {
return pizza.getIngredients().stream().mapToInt(Ingredient::getPrice).sum();
}
static Pizza mostExpensiveVegetarianPizza(Collection<Pizza> pizzas) {
return pizzas.stream()
.filter(Pizza::isVegetarian)
.max(Comparator.comparingInt(Pizza::price))
.orElseThrow(() -> new IllegalArgumentException("no veggie pizzas"));
}
}
Run Code Online (Sandbox Code Playgroud)
如果你想Ingredient.getPrice()返回a double,你会使用Stream.mapToDouble()in Pizza.price()和Comparator.comparingDouble()in Pizza.mostExpensiveVegetarianPizza().
| 归档时间: |
|
| 查看次数: |
240 次 |
| 最近记录: |