Skip to content

Commit 88f99f5

Browse files
committed
Stream接口
1 parent fb5b170 commit 88f99f5

File tree

5 files changed

+257
-17
lines changed

5 files changed

+257
-17
lines changed
Lines changed: 248 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,248 @@
1+
##Stream类
2+
3+
java.util.Stream 表示能应用在一组元素上一次执行的操作序列。
4+
Stream 操作分为中间操作或者最终操作两种,最终操作返回一特定类型的计算结果,
5+
而中间操作返回Stream本身,这样你就可以将多个操作依次串起来。Stream 的
6+
创建需要指定一个数据源,比如 java.util.Collection的子类,List或者Set,
7+
Map不支持。Stream的操作可以串行执行或者并行执行。
8+
- **Stream的基本接口**
9+
```
10+
List<String> stringCollection = new ArrayList<>();
11+
stringCollection.add("ddd2");
12+
stringCollection.add("aaa2");
13+
stringCollection.add("bbb1");
14+
stringCollection.add("aaa1");
15+
stringCollection.add("bbb3");
16+
stringCollection.add("ccc");
17+
stringCollection.add("bbb2");
18+
stringCollection.add("ddd1");
19+
```
20+
####Filter 过滤.
21+
22+
Filter通过一个predicate接口来过滤并只保留符合条件的元素,该操作属于中间操作,
23+
所以我们可以在过滤后的结果来应用其他Stream操作(比如forEach)。forEach
24+
需要一个函数来对过滤后的元素依次执行。forEach是一个最终操作,所以我们不
25+
能在forEach之后来执行其他Stream操作。
26+
```
27+
stringCollection
28+
.stream()
29+
.filter((s) -> s.startsWith("a"))
30+
.forEach(System.out::println);
31+
```
32+
####Sorted 排序.
33+
34+
Sorted是一个中间操作,返回的是排序好后的Stream。如果你不指定一个自定义的Comparator则会使用默认排序.
35+
```
36+
stringCollection
37+
.stream()
38+
.sorted()
39+
.forEach(System.out::println);
40+
System.out.println(stringCollection);//原数据源不会被改变
41+
```
42+
####Map
43+
44+
中间操作map会将元素根据指定的Function接口来依次将元素转成另外的对象.
45+
```
46+
stringCollection
47+
.stream()
48+
.map(String::toUpperCase)
49+
.map((s)->s+" space")
50+
.sorted((a, b) -> b.compareTo(a))
51+
.forEach(System.out::println);
52+
```
53+
####Match
54+
55+
Stream提供了多种匹配操作,允许检测指定的Predicate是否匹配整个Stream。
56+
所有的匹配操作都是最终操作,并返回一个boolean类型的值。
57+
```
58+
boolean anyStartsWithA = stringCollection
59+
.stream()
60+
.anyMatch((s) -> s.startsWith("a"));
61+
System.out.println(anyStartsWithA); // true
62+
63+
boolean allStartsWithA = stringCollection
64+
.stream()
65+
.allMatch((s) -> s.startsWith("a"));
66+
System.out.println(allStartsWithA); // false
67+
68+
boolean noneStartsWithZ = stringCollection
69+
.stream()
70+
.noneMatch((s) -> s.startsWith("z"));
71+
System.out.println(noneStartsWithZ); // true
72+
```
73+
####Count
74+
75+
计数是一个最终操作,返回Stream中元素的个数,返回值类型是long。
76+
```
77+
long startsWithB = stringCollection
78+
.stream()
79+
.filter((s) -> s.startsWith("b"))
80+
.count();
81+
System.out.println(startsWithB); // 3
82+
```
83+
####Reduce
84+
85+
Reduce是一个最终操作,允许通过指定的函数来讲stream中的多个元素规约为一个元素,规约后的结果是通过Optional接口表示的。
86+
```
87+
Optional<String> reduced =
88+
stringCollection
89+
.stream()
90+
.sorted()
91+
.reduce((s1, s2) -> s1 + "#" + s2);
92+
93+
reduced.ifPresent(System.out::println);
94+
##:aaa1#aaa2#bbb1#bbb2#bbb3#ccc#ddd1#ddd2
95+
```
96+
- **并行stream和串行stream**
97+
####并行stream
98+
99+
```
100+
List<String> values = new ArrayList<>(MAX);
101+
for (int i = 0; i < MAX; i++) {
102+
UUID uuid = UUID.randomUUID();
103+
values.add(uuid.toString());
104+
}
105+
106+
long t0 = System.nanoTime();
107+
long count = values.stream().sorted().count();
108+
System.out.println(count);
109+
110+
long t1 = System.nanoTime();
111+
long millis = TimeUnit.NANOSECONDS.toMillis(t1 - t0);
112+
System.out.println(String.format("sequential sort took: %d ms", millis));
113+
```
114+
####串行stream
115+
116+
串行stream是在运行时将数据划分成了多个块,然后将数据块分配给合适的处理器去处理。
117+
只有当所有块都处理完成了,才会执行之后的代码。
118+
119+
```
120+
List<String> values = new ArrayList<>(MAX);
121+
for (int i = 0; i < MAX; i++) {
122+
UUID uuid = UUID.randomUUID();
123+
values.add(uuid.toString());
124+
}
125+
126+
long t0 = System.nanoTime();
127+
long count = values.parallelStream().sorted().count();
128+
System.out.println(count);
129+
130+
long t1 = System.nanoTime();
131+
long millis = TimeUnit.NANOSECONDS.toMillis(t1 - t0);
132+
System.out.println(String.format("parallel sort took: %d ms", millis));
133+
```
134+
时间结果比较:
135+
```
136+
1000000
137+
sequential sort took: 717 ms
138+
1000000
139+
parallel sort took: 303 ms
140+
```
141+
- **IntStream接口**
142+
143+
IntStream接口是stream的一种,继承了BaseStream接口。
144+
####range
145+
```
146+
IntStream.range(0, 10)
147+
.forEach(i -> {
148+
if (i % 2 == 1) System.out.print(i+" ");
149+
});
150+
##:1 3 5 7 9
151+
152+
OptionalInt reduced1 =
153+
IntStream.range(0, 10)
154+
.reduce((a, b) -> a + b);
155+
System.out.println(reduced1.getAsInt());
156+
157+
int reduced2 =
158+
IntStream.range(0, 10)
159+
.reduce(7, (a, b) -> a + b);
160+
System.out.println(reduced2);
161+
##:45
162+
52
163+
```
164+
####sum
165+
```
166+
System.out.println(IntStream.range(0, 10).sum());
167+
```
168+
- **Stream的应用**
169+
```
170+
Map<String, Integer> unsortMap = new HashMap<>();
171+
unsortMap.put("z", 10);
172+
unsortMap.put("b", 5);
173+
unsortMap.put("a", 6);
174+
unsortMap.put("c", 20);
175+
unsortMap.put("d", 1);
176+
unsortMap.put("e", 7);
177+
unsortMap.put("y", 8);
178+
unsortMap.put("n", 99);
179+
unsortMap.put("j", 50);
180+
unsortMap.put("m", 2);
181+
unsortMap.put("f", 9);
182+
```
183+
使用stream类来对map的value排序
184+
```
185+
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
186+
Map<K, V> result = new LinkedHashMap<>();
187+
map.entrySet().parallelStream()
188+
.sorted((o1, o2) -> (o2.getValue()).compareTo(o1.getValue()))
189+
.forEachOrdered(x -> result.put(x.getKey(), x.getValue()));
190+
return result;
191+
}
192+
System.out.println(sortByValue(unsortMap));
193+
##:{n=99, j=50, c=20, z=10, f=9, y=8, e=7, a=6, b=5, m=2, d=1}
194+
```
195+
```
196+
List<Object> list = new ArrayList<>();
197+
JSONObject data1 = new JSONObject();
198+
data1.put("type", "支出");
199+
data1.put("money", 500);
200+
JSONObject data2 = new JSONObject();
201+
data2.put("type", "收入");
202+
data2.put("money", 1000);
203+
JSONObject data3 = new JSONObject();
204+
data3.put("type", "借贷");
205+
data3.put("money", 100);
206+
list.add(data1);
207+
list.add(data2);
208+
list.add(data3);
209+
```
210+
使用stream类来处理list里面的json数据
211+
```
212+
/**
213+
* 按money的值来排列json
214+
*/
215+
list.stream()
216+
.filter(x -> JSONObject.fromObject(x).containsKey("money"))
217+
.sorted((b, a) -> Integer.valueOf(JSONObject.fromObject(a).getInt("money")).compareTo(JSONObject.fromObject(b)
218+
.getInt("money")))
219+
.forEach(System.out::println);
220+
/**
221+
* 找到最小的money
222+
*/
223+
Integer min = list.stream()
224+
.filter(x -> JSONObject.fromObject(x).containsKey("money"))
225+
.map(x -> JSONObject.fromObject(x).getInt("money"))
226+
.sorted()
227+
.findFirst()
228+
.get();
229+
System.out.println(min);
230+
/**
231+
* 计算type的数目
232+
*/
233+
Map<String, Integer> type_count = new HashMap<>();
234+
list.stream()
235+
.filter(x -> JSONObject.fromObject(x).containsKey("type"))
236+
.map(x -> JSONObject.fromObject(x).getString("type"))
237+
.forEach(x -> {
238+
if (type_count.containsKey(x)) type_count.put(x, type_count.get(x) + 1);
239+
else type_count.put(x, 1);
240+
});
241+
System.out.println(type_count.toString());
242+
##:
243+
{"type":"收入","money":1000}
244+
{"type":"支出","money":500}
245+
{"type":"借贷","money":100}
246+
100
247+
{借贷=1, 收入=1, 支出=1}
248+
```

src/main/java/com/xu/java8/Stream/Streams1.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ public static void main(String[] args) {
9696
System.out.println(startsWithB); // 3
9797

9898
/**
99-
* 这是一个最终操作,允许通过指定的函数来讲stream中的多个元素规约为一个元素,规越后的结果是通过Optional接口表示的
99+
* 这是一个最终操作,允许通过指定的函数来讲stream中的多个元素规约为一个元素,规约后的结果是通过Optional接口表示的
100100
*/
101101
System.out.println("--------------reducing----------------");
102102
Optional<String> reduced =

src/main/java/com/xu/java8/Stream/Streams3.java

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -22,15 +22,11 @@ public static void sortSequential() {
2222
values.add(uuid.toString());
2323
}
2424

25-
// sequential
26-
2725
long t0 = System.nanoTime();
28-
2926
long count = values.stream().sorted().count();
3027
System.out.println(count);
3128

3229
long t1 = System.nanoTime();
33-
3430
long millis = TimeUnit.NANOSECONDS.toMillis(t1 - t0);
3531
System.out.println(String.format("sequential sort took: %d ms", millis));
3632
}
@@ -42,15 +38,11 @@ public static void sortParallel() {
4238
values.add(uuid.toString());
4339
}
4440

45-
// sequential
46-
4741
long t0 = System.nanoTime();
48-
4942
long count = values.parallelStream().sorted().count();
5043
System.out.println(count);
5144

5245
long t1 = System.nanoTime();
53-
5446
long millis = TimeUnit.NANOSECONDS.toMillis(t1 - t0);
5547
System.out.println(String.format("parallel sort took: %d ms", millis));
5648
}

src/main/java/com/xu/java8/Stream/Streams4.java

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,8 @@ public static void main(String[] args) {
2424
.forEach(i -> {
2525
if (i % 2 == 1) System.out.print(i+" ");
2626
});
27-
27+
System.out.println();
28+
System.out.println(IntStream.range(0, 10).sum());
2829
System.out.println();
2930
IntStream.range(0, 10)
3031
.filter(i -> i % 2 == 1)

src/main/java/com/xu/java8/Stream/Streams6.java

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -50,9 +50,9 @@ public static void main(String args[]) {
5050
/**
5151
* 找到最小的money
5252
*/
53-
Integer min=list.stream()
53+
Integer min = list.stream()
5454
.filter(x -> JSONObject.fromObject(x).containsKey("money"))
55-
.map(x->JSONObject.fromObject(x).getInt("money"))
55+
.map(x -> JSONObject.fromObject(x).getInt("money"))
5656
.sorted()
5757
.findFirst()
5858
.get();
@@ -74,12 +74,11 @@ public static void main(String args[]) {
7474
/**
7575
* 使用stream类来对map的value排序(并行排序,逆序)
7676
*/
77-
public static <K, V extends Comparable<? super V>> Map<K, V>
78-
sortByValue(Map<K, V> map) {
77+
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
7978
Map<K, V> result = new LinkedHashMap<>();
80-
map.entrySet().parallelStream().sorted((o1, o2) -> (o2.getValue()).compareTo(o1.getValue())).forEachOrdered(x ->
81-
result.put(x.getKey(), x
82-
.getValue()));
79+
map.entrySet().parallelStream()
80+
.sorted((o1, o2) -> (o2.getValue()).compareTo(o1.getValue()))
81+
.forEachOrdered(x -> result.put(x.getKey(), x.getValue()));
8382
return result;
8483
}
8584
}

0 commit comments

Comments
 (0)