-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsection.java.util.stream.xml
More file actions
604 lines (555 loc) · 17.7 KB
/
section.java.util.stream.xml
File metadata and controls
604 lines (555 loc) · 17.7 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
<?xml version="1.0" encoding="UTF-8"?>
<chapter id="index"><?dbhtml dir="stream" ?>
<title>Stream</title>
<section id="Stream.of">
<title>Stream.of</title>
<programlisting>
<![CDATA[
Stream<String> stream = Stream.of("Hollis", "HollisChuang", "hollis", "Hello", "HelloWorld", "Hollis");
]]>
</programlisting>
<programlisting>
<![CDATA[
Stream<Integer> mystream = Stream.of(10, 12, 14, 16);
]]>
</programlisting>
</section>
<section id="Stream.ofNullable">
<title>Stream.ofNullable</title>
<para>增加单个参数构造方法,可为null</para>
<screen>
<![CDATA[
Stream.ofNullable(null).count(); // 0
]]>
</screen>
</section>
<section id="stream.filter">
<title>filter</title>
<para>filter 方法用于通过设置的条件过滤出元素。以下代码片段使用 filter 方法过滤掉空字符串:</para>
<programlisting>
<![CDATA[
List<String> strings = Arrays.asList("Hollis", "", "HollisChuang", "H", "hollis");
strings.stream().filter(string -> !string.isEmpty()).forEach(System.out::println);
]]>
</programlisting>
</section>
<section id="stream.map">
<title>map</title>
<para>map 方法用于映射每个元素到对应的结果,以下代码片段使用 map 输出了元素对应的平方数:</para>
<programlisting>
<![CDATA[
List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
numbers.stream().map( i -> i*i).forEach(System.out::println);
//9,4,4,9,49,9,25
]]>
</programlisting>
</section>
<section id="stream.peek">
<title>peek 打印调试信息</title>
<programlisting>
<![CDATA[
package cn.netkiller.test;
import lombok.Data;
import java.io.IOException;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@Data
public class Test {
public static void main(String[] args) throws IOException {
Stream.of("one", "two", "three", "four").filter(e -> e.length() > 3)
.peek(e -> System.out.println("Before value: " + e))
.map(String::toUpperCase)
.peek(e -> System.out.println("After value: " + e))
.collect(Collectors.toList());
}
}
]]>
</programlisting>
<programlisting>
<![CDATA[
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
numbers.stream()
.peek(n -> System.out.println("原始元素:" + n))
.filter(n -> n % 2 == 0)
.peek(n -> System.out.println("过滤后元素:" + n))
.collect(Collectors.toList());
]]>
</programlisting>
</section>
<section id="stream.limit">
<title>limit/skip</title>
<para>limit 返回 Stream 的前面 n 个元素;skip 则是扔掉前 n 个元素。以下代码片段使用 limit
方法保理4个元素:
</para>
<programlisting>
<![CDATA[
List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
numbers.stream().limit(4).forEach(System.out::println);
//3,2,2,3
]]>
</programlisting>
</section>
<section id="stream.sorted">
<title>sorted</title>
<para>sorted 方法用于对流进行排序。以下代码片段使用 sorted 方法进行排序:</para>
<programlisting>
<![CDATA[
List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
numbers.stream().sorted().forEach(System.out::println);
//2,2,3,3,3,5,7
]]>
</programlisting>
</section>
<section id="stream.distinct">
<title>distinct</title>
<para>distinct主要用来去重,以下代码片段使用 distinct 对元素进行去重:</para>
<programlisting>
<![CDATA[
List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
numbers.stream().distinct().forEach(System.out::println);
//3,2,7,5
]]>
</programlisting>
</section>
<section id="stream.forEach">
<title>forEach</title>
<para>Stream 提供了方法 'forEach' 来迭代流中的每个数据。以下代码片段使用 forEach 输出了10个随机数:
</para>
<programlisting>
<![CDATA[
Stream<String> mystream = Stream.of("AA", "BB", "CC", "DD");
mystream.forEach(e -> System.out.println(e));
]]>
</programlisting>
<programlisting>
<![CDATA[
Random random = new Random();
random.ints().limit(10).forEach(System.out::println);
]]>
</programlisting>
<para>创建线程</para>
<programlisting>
<![CDATA[
public static void main(String[] args) {
Stream.of("线程1","线程2").forEach(n->new Thread(n) {
public void run(){
Test.sleep();
}
}.start());
}
]]>
</programlisting>
</section>
<section id="stream.count">
<title>count</title>
<para>count用来统计流中的元素个数。</para>
<programlisting>
<![CDATA[
List<String> strings = Arrays.asList("Hollis", "HollisChuang", "hollis","Hollis666", "Hello", "HelloWorld", "Hollis");
System.out.println(strings.stream().count());
//7
]]>
</programlisting>
</section>
<section id="stream.toList">
<title>流转列表</title>
<programlisting>
<![CDATA[
Stream<String> stream = Stream.of("Apple", "Banana", "Coconut");
List<String> fruits = stream.toList();
fruits.forEach(System.out::println);
]]>
</programlisting>
</section>
<section id="stream.collect">
<title>collect</title>
<para>collect就是一个归约操作,可以接受各种做法作为参数,将流中的元素累积成一个汇总结果:</para>
<section>
<title>Collectors.toList() 列表转字符串</title>
<programlisting>
<![CDATA[
List<String> strings = Arrays.asList("Hollis", "HollisChuang", "hollis","Hollis666", "Hello", "HelloWorld", "Hollis");
strings = strings.stream().filter(string -> string.startsWith("Hollis")).collect(Collectors.toList());
System.out.println(strings);
//Hollis, HollisChuang, Hollis666, Hollis
]]>
</programlisting>
<para>最佳替代方案</para>
<programlisting>
<![CDATA[
Stream<String> stream = Stream.of("Apple", "Banana", "Coconut");
List<String> fruits = stream.toList();
fruits.forEach(System.out::println);
]]>
</programlisting>
</section>
<section>
<title>Collectors.joining() 连接字符串</title>
<para>连接字符串</para>
<programlisting>
<![CDATA[
Stream<String> stream = Stream.of("https://", "www.netkiller.cn", "/java/index.html");
String url = stream.collect(Collectors.joining());
System.out.println(url);
]]>
</programlisting>
</section>
<section>
<title>转 Set Collectors.toSet()</title>
<programlisting>
<![CDATA[
Set<String> studentNames=students.stream().map(student -> student.getName()).collect(Collectors.toSet());
]]>
</programlisting>
</section>
<section id="Collectors.teeing">
<title>Collectors.teeing()</title>
<para>teeing
收集器已公开为静态方法Collectors::teeing。该收集器将其输入转发给其他两个收集器,然后将它们的结果使用函数合并。
</para>
<programlisting>
<![CDATA[
package cn.netkiller.demo;
public class Student {
public String name;
public int score;
public Student(String name, int score) {
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
@Override
public String toString() {
return "Student [name=" + name + ", score=" + score + "]";
}
}
]]>
</programlisting>
<programlisting>
<![CDATA[
package cn.netkiller.demo;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class Test {
public Test() {
}
public static void main(String[] args) {
List<Student> list = Arrays.asList(new Student("Neo", 80), new Student("Tom", 60), new Student("Jerry", 70));
// 平均分 总分
String result = list.stream().collect(Collectors.teeing(Collectors.averagingInt(Student::getScore), Collectors.summingInt(Student::getScore), (s1, s2) -> s1 + ":" + s2));
// 最低分 最高分
String result2 = list.stream().collect(Collectors.teeing(Collectors.minBy(Comparator.comparing(Student::getScore)), Collectors.maxBy(Comparator.comparing(Student::getScore)), (s1, s2) -> s1.orElseThrow() + ":" + s2.orElseThrow()));
System.out.println(result);
System.out.println(result2);
}
}
]]>
</programlisting>
</section>
</section>
<section id="stream.takeWhile">
<title>takeWhile 和 dropWhile</title>
<para>增加 takeWhile 和 dropWhile 方法</para>
<screen>
<![CDATA[
Stream.of(1, 2, 3, 2, 1)
.takeWhile(n -> n < 3)
.collect(Collectors.toList()); // [1, 2]
]]>
</screen>
<para>从开始计算,当 n < 3 时就截止</para>
<screen>
<![CDATA[
Stream.of(1, 2, 3, 2, 1)
.dropWhile(n -> n < 3)
.collect(Collectors.toList()); // [3, 2, 1]
]]>
</screen>
</section>
<section id="Stream.concat">
<title>合并 Stream</title>
<para>前方插队</para>
<programlisting>
<![CDATA[
Stream<Integer> stream = Stream.of(1, 2, 3, 4);
//Prepend 0 to the stream
Stream<Integer> prependedStream = Stream.concat(Stream.of(0), stream);
//Verify Stream
prependedStream.forEach(System.out::print); //Prints 01234
]]>
</programlisting>
<para>末尾追加</para>
<programlisting>
<![CDATA[
Stream<Integer> stream = Stream.of(1, 2, 3, 4);
//Append 5 and 6 to the stream
Stream<Integer> appenededStream = Stream.concat(stream, Stream.of(5, 6));
//Verify Stream
appenededStream.forEach(System.out::print); //Prints 123456
]]>
</programlisting>
</section>
<section id="stream.mapToObj">
<title>mapToObj</title>
<para>mapToObj 会返字符串 “message 1” </para>
<programlisting>
<![CDATA[
IntStream.range(0, 11).mapToObj(i -> "message " + i).peek(message -> publisher.submit(message)).forEach(System.out::println);
]]>
</programlisting>
</section>
<section id="stream.Collectors">
<title>Collectors</title>
<screen>
<![CDATA[
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class StreamJoinWithNewline {
public static void main(String[] args) {
// 1. 示例1:从List创建Stream<String>
List<String> stringList = Arrays.asList("第一行", "第二行", "第三行", "第四行");
String joinedByNewline1 = stringList.stream()
.collect(Collectors.joining("\n")); // 关键:用"\n"作为分隔符
System.out.println("从List生成的拼接结果:");
System.out.println(joinedByNewline1);
// 输出结果(带换行):
// 第一行
// 第二行
// 第三行
// 第四行
// 2. 示例2:直接创建Stream<String>(如动态生成的字符串流)
Stream<String> stringStream = Stream.of("Apple", "Banana", "Cherry", "Date");
String joinedByNewline2 = stringStream
.collect(Collectors.joining("\n"));
System.out.println("\n直接Stream生成的拼接结果:");
System.out.println(joinedByNewline2);
// 输出结果(带换行):
// Apple
// Banana
// Cherry
// Date
}
}
]]>
</screen>
<section>
<title></title>
<screen>
<![CDATA[
Stream<String> lines = Stream.of("Hello", "World", "Java Stream");
// 前缀加"【", 后缀加"】",元素间用"\n"分隔
String resultWithPrefixSuffix = lines.collect(Collectors.joining(
"\n", // 元素分隔符(换行)
"【", // 整体前缀
"】" // 整体后缀
));
System.out.println(resultWithPrefixSuffix);
// 输出结果:
// 【Hello
// World
// Java Stream】
]]>
</screen>
</section>
<section>
<title>过滤空值</title>
<screen>
<![CDATA[
String joinedWithNoNull = stringList.stream()
.filter(Objects::nonNull) // 过滤null元素
.collect(Collectors.joining("\n"));
]]>
</screen>
</section>
</section>
<section id="stream.example">
<title>混合使用的例子</title>
<programlisting>
<![CDATA[
List<String> strings = Arrays.asList("Hollis", "HollisChuang", "hollis", "Hello", "HelloWorld", "Hollis");
Stream s = strings.stream().filter(string -> string.length()<= 6).map(String::length).sorted().limit(3)
.distinct();
]]>
</programlisting>
<section id="stream.list">
<title>List to Stream</title>
<programlisting>
<![CDATA[
List<String> strings = Arrays.asList("Hollis", "HollisChuang", "hollis", "Hello", "HelloWorld", "Hollis");
Stream<String> stream = strings.stream();
]]>
</programlisting>
</section>
</section>
<section id="streamSupplier">
<title>流复用 streamSupplier</title>
<programlisting>
<![CDATA[
Supplier<Stream<String>> streamSupplier =
() -> Stream.of("d2", "a2", "b1", "b3", "c")
.filter(s -> s.startsWith("a"));
]]>
</programlisting>
</section>
<section id="parallelStream">
<title>Parallel Streams(并行流)</title>
<programlisting>
<![CDATA[
Arrays.asList("a1", "a2", "b1", "c2", "c1")
.parallelStream()
.filter(s -> {
System.out.format("filter: %s [%s]\n",
s, Thread.currentThread().getName());
return true;
})
.map(s -> {
System.out.format("map: %s [%s]\n",
s, Thread.currentThread().getName());
return s.toUpperCase();
})
.sorted((s1, s2) -> {
System.out.format("sort: %s <> %s [%s]\n",
s1, s2, Thread.currentThread().getName());
return s1.compareTo(s2);
})
.forEach(s -> System.out.format("forEach: %s [%s]\n",
s, Thread.currentThread().getName()));
]]>
</programlisting>
<programlisting>
<![CDATA[
List<Person> persons = Arrays.asList(
new Person("Max", 18),
new Person("Peter", 23),
new Person("Pamela", 23),
new Person("David", 12));
persons
.parallelStream()
.reduce(0,
(sum, p) -> {
System.out.format("accumulator: sum=%s; person=%s [%s]\n",
sum, p, Thread.currentThread().getName());
return sum += p.age;
},
(sum1, sum2) -> {
System.out.format("combiner: sum1=%s; sum2=%s [%s]\n",
sum1, sum2, Thread.currentThread().getName());
return sum1 + sum2;
});
]]>
</programlisting>
</section>
<section id="IntStream">
<title>IntStream</title>
<programlisting>
<![CDATA[
List<Picture> list = new ArrayList<Picture>();
IntStream.range(1, 10).forEach(i -> {
Picture picture = new Picture();
picture.setId(Long.valueOf(i));
picture.setImage("https://www.netkiller.cn/images/" + i + ".png");
list.add(picture);
});
]]>
</programlisting>
<programlisting>
<![CDATA[
package cn.netkiller;
import java.util.stream.DoubleStream;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
public class StreamOfDemo {
public static void main(String[] args) {
System.out.println("--- IntStream ---");
IntStream intStream = IntStream.of(8, 16, 32);
intStream.forEach(e -> System.out.println(e));
System.out.println("--- LongStream ---");
LongStream longStream = LongStream.of(135L, 246L, 1024L);
longStream.forEach(e -> System.out.println(e));
System.out.println("--- DoubleStream ---");
DoubleStream doubleStream = DoubleStream.of(123.56, 456.87, 789.65);
doubleStream.forEach(e -> System.out.println(e));
}
}
]]>
</programlisting>
</section>
<section id="LongStream">
<title>LongStream</title>
<programlisting>
<![CDATA[
LongStream longStream = LongStream.generate(() -> new Random().nextLong()).limit(5);
longStream.forEach(v -> System.out.println(v));
]]>
</programlisting>
</section>
<section id="DoubleStream">
<title>DoubleStream</title>
<programlisting>
<![CDATA[
System.out.println("--- DoubleStream ---");
DoubleStream doubleStream = DoubleStream.of(123.56, 456.87, 789.65);
doubleStream.forEach(e -> System.out.println(e));
System.out.println("--- DoubleStream.generate() ---");
DoubleStream doubleStream = DoubleStream.generate(() -> new Random().nextDouble()).limit(5);
doubleStream.forEach(v -> System.out.println(v));
]]>
</programlisting>
</section>
<section>
<title>例子</title>
<section>
<title>Markdown 转 CSV</title>
<programlisting>
<![CDATA[
package cn.netkiller.test;
import lombok.SneakyThrows;
import java.util.Arrays;
import java.util.List;
public class Test {
@SneakyThrows
public static void main(String[] args) {
String markdown = """
# Table
| id | name | start | finish | resource | progress | predecessor | milestone | parent |
| ------ | ------ | -------- |
| 1 | 测试麦克风 | 2025-07-01 | 2025-07-02 | 工程师 | 1 | 0 | False | 0 |
| 2 | 设备送检 | 2025-07-03 | 2025-07-04 | 设计师 | 1 | 1 | False | 0 |
| 3 | 完成包装 | 2025-07-05 | 2025-07-10 | 设计师 | 1 | 1 | False | 0 |
| 4 | 竞品评估 | 2025-07-02 | 2025-07-04 | 设计师 | 1 | 0 | True | 0 |
| 5 | 分析报告 | 2025-07-08 | 2025-07-15 | 设计师 | 1 | 0 | False | 0 |
| 6 | 集成测试 | 2025-07-01 | 2025-07-06 | 设计师 | 1 | 0 | False | 0 |
https://www.netkiller.cn/java/
""";
// Arrays.stream(markdown.split("\n")).filter(s -> s.contains("| ")).skip(0).map(line -> {
// return line.replaceAll(" \\| ", ",").replaceFirst("\\| ", "").replaceFirst(" \\|", "");
// }).forEach(v -> {
// System.out.println(v);
// });
List<String> lines = Arrays.stream(markdown.split("\n")).filter(s -> s.contains("| ")).skip(0).map(line -> {
return line.replaceAll(" \\| ", ",").replaceFirst("\\| ", "").replaceFirst(" \\|", "");
}).filter(s -> !s.contains("-,-")).toList();
String csv = String.join("\n", lines);
System.out.println(csv);
}
}
]]>
</programlisting>
</section>
</section>
</chapter>