Skip to content

Commit 772c78a

Browse files
committed
[add] add example of Stream Operation
1 parent 0366f87 commit 772c78a

File tree

3 files changed

+40
-1
lines changed

3 files changed

+40
-1
lines changed

java8/README.md

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,11 @@
66

77
## lambda 表达式
88

9-
- FilteringApples: 传递代码的例子,展示方法引用和Lambda
9+
- FilteringApples: 传递代码的例子,展示方法引用和 Lambda
1010

1111

1212
## steam API
1313

14+
- Dish:
15+
- StreamBasic: 指令式和函数式分别挑选低热量食物名
16+
- StreamOperation: 流操作:中间操作和终端操作

java8/src/main/java/com/brianway/learning/java8/streamapi/Dish.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,9 @@
33
import java.util.Arrays;
44
import java.util.List;
55

6+
/**
7+
* 菜肴类
8+
*/
69
public class Dish {
710

811
private final String name;
@@ -44,6 +47,9 @@ public String toString() {
4447
return name;
4548
}
4649

50+
/**
51+
* 菜肴列表
52+
*/
4753
public static final List<Dish> menu =
4854
Arrays.asList(new Dish("pork", false, 800, Dish.Type.MEAT),
4955
new Dish("beef", false, 700, Dish.Type.MEAT),
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package com.brianway.learning.java8.streamapi;
2+
3+
import static com.brianway.learning.java8.streamapi.Dish.menu;
4+
5+
import java.util.List;
6+
import java.util.stream.Collectors;
7+
8+
/**
9+
* Created by brian on 17/2/28.
10+
* 流操作:中间操作和终端操作
11+
* 流的延迟性质
12+
* 1. limit 操作,短路
13+
* 2. filter 和 map 操作, 循环合并
14+
*/
15+
public class StreamOperation {
16+
public static void main(String[] args) {
17+
List<String> names = menu.stream()
18+
.filter(d -> {
19+
System.out.println("filtering " + d.getName());
20+
return d.getCalories() > 300;
21+
})
22+
.map(d -> {
23+
System.out.println("mapping " + d.getName());
24+
return d.getName();
25+
})
26+
.limit(3)
27+
.collect(Collectors.toList());
28+
System.out.println(names);
29+
}
30+
}

0 commit comments

Comments
 (0)