-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStreamCollect.java
More file actions
60 lines (51 loc) · 1.69 KB
/
StreamCollect.java
File metadata and controls
60 lines (51 loc) · 1.69 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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package example.StreamExample;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
/**
* Reference
* - https://mrbird.cc/java8stream2.html
* - https://blog.tonycube.com/2015/10/java-java8-3-stream.html
*/
public class StreamCollect {
public static void main(String[] args) {
List<Dish> list = 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, 300, Dish.Type.FISH),
new Dish("salmon", false, 450, Dish.Type.FISH)
);
list.stream()
.collect(Collectors.maxBy(Comparator.comparingInt(Dish::getCalories)))
.ifPresent(System.out::println);
}
}
class Dish {
public enum Type {MEAT, FISH, OTHER}
private final String name;
private final boolean vegetarian;
private final int calories;
private final Type type;
public Dish(String name, boolean vegetarian, int calories, Type type) {
this.name = name;
this.vegetarian = vegetarian;
this.calories = calories;
this.type = type;
}
public String toString() {
return this.getName();
}
public String getName() {
return this.name;
}
public int getCalories() {
return this.calories;
}
// ignore the getter, setter.
}