forked from benjaminwhx/p_java8InAction
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReducing.java
More file actions
37 lines (30 loc) · 1.22 KB
/
Reducing.java
File metadata and controls
37 lines (30 loc) · 1.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package chapter6;
import entity.Dish;
import static entity.Dish.menu;
import static java.util.stream.Collectors.*;
/**
* User: 吴海旭
* Date: 2016-11-22
* Time: 上午11:34
* 6.2:归约和汇总
*/
public class Reducing {
public static void main(String[] args) {
System.out.println("Total calories in menu: " + calculateTotalCalories());
System.out.println("Total calories in menu: " + calculateTotalCaloriesWithMethodReference());
System.out.println("Total calories in menu: " + calculateTotalCaloriesWithoutCollectors());
System.out.println("Total calories in menu: " + calculateTotalCaloriesUsingSum());
}
private static int calculateTotalCalories() {
return menu.stream().collect(reducing(0, Dish::getCalories, (i, j) -> i + j));
}
private static int calculateTotalCaloriesWithMethodReference() {
return menu.stream().collect(reducing(0, Dish::getCalories, Integer::sum));
}
private static int calculateTotalCaloriesWithoutCollectors() {
return menu.stream().map(Dish::getCalories).reduce(Integer::sum).get();
}
private static int calculateTotalCaloriesUsingSum() {
return menu.stream().mapToInt(Dish::getCalories).sum();
}
}