直接在流上使用 stream.max() 与使用 stream.collect(...) 有什么区别
what is the difference in using stream.max() on the stream directly vs using stream.collect(...)
有什么区别b/w这两种从菜单列表中找到最高卡路里菜肴的方法?
List<Dish> menu = Arrays.asList( new Dish("pork", false, 800, Dish.Type.MEAT),
new Dish("beef", false, 700, Dish.Type.MEAT),
new Dish("chicken", false, 400, Dish.Type.MEAT),
new Dish("french fries", true, 530, Dish.Type.OTHER),
new Dish("rice", true, 350, Dish.Type.OTHER),
new Dish("season fruit", true, 120, Dish.Type.OTHER),
new Dish("pizza", true, 550, Dish.Type.OTHER),
new Dish("prawns", false, 400, Dish.Type.FISH),
new Dish("salmon", false, 450, Dish.Type.FISH));
Optional<Dish> maxCalorieDish = menu.stream()
.max((c1,c2) -> c1.getCalories().compareTo(c2.getCalories()));
System.out.println(maxCalorieDish);
Optional<Dish> maxCalorieDish1 = menu.stream()
.collect(maxBy((c1,c2) -> c1.getCalories().compareTo(c2.getCalories())));
System.out.println(maxCalorieDish1);
我会说可读性,主要是如果你使用这个语法:
menu.stream().max(Comparator::comparing(Dish::getCalories));
我也能找到 this question 非常相似
有什么区别b/w这两种从菜单列表中找到最高卡路里菜肴的方法?
List<Dish> menu = Arrays.asList( new Dish("pork", false, 800, Dish.Type.MEAT),
new Dish("beef", false, 700, Dish.Type.MEAT),
new Dish("chicken", false, 400, Dish.Type.MEAT),
new Dish("french fries", true, 530, Dish.Type.OTHER),
new Dish("rice", true, 350, Dish.Type.OTHER),
new Dish("season fruit", true, 120, Dish.Type.OTHER),
new Dish("pizza", true, 550, Dish.Type.OTHER),
new Dish("prawns", false, 400, Dish.Type.FISH),
new Dish("salmon", false, 450, Dish.Type.FISH));
Optional<Dish> maxCalorieDish = menu.stream()
.max((c1,c2) -> c1.getCalories().compareTo(c2.getCalories()));
System.out.println(maxCalorieDish);
Optional<Dish> maxCalorieDish1 = menu.stream()
.collect(maxBy((c1,c2) -> c1.getCalories().compareTo(c2.getCalories())));
System.out.println(maxCalorieDish1);
我会说可读性,主要是如果你使用这个语法:
menu.stream().max(Comparator::comparing(Dish::getCalories));
我也能找到 this question 非常相似