创建流的方式
1/**
2 * many ways to create a {@link Stream} in Java api.
3 *
4 * @author wangy
5 * @version 1.0
6 * @date 2021/1/12 / 22:35
7 */
8public class CreateStream {
9
10 public static <T> void show(String title, Stream<T> stream) {
11 final int SIZE = 10;
12 List<T> firstElements = stream
13 .limit(SIZE + 1)
14 .collect(Collectors.toList());
15 System.out.print(title + ": ");
16 for (int i = 0; i < firstElements.size(); i++) {
17 if (i > 0)
18 System.out.print(", ");
19 if (i < SIZE)
20 System.out.print(firstElements.get(i));
21 else
22 System.out.print("...");
23 }
24 System.out.println();
25 }
26
27 public static void main(String[] args) throws IOException {
28 Path path = Paths.get("java/resources/txt/alice30.txt");
29 String contents = new String(Files.readAllBytes(path),
30 StandardCharsets.UTF_8);
31
32 // \\PL+ 将contents按非unicode字符分割成流
33 Stream<String> words = Stream.of(contents.split("\\PL+"));
34 show("words", words);
35
36 Stream<String> song = Stream.of("gently", "down", "the", "stream");
37 show("song", song);
38
39 Stream<String> silence = Stream.empty();
40 show("silence", silence);
41
42 Stream<String> echos = Stream.generate(() -> "Echo");
43 show("echos", echos);
44
45 Stream<Double> randoms = Stream.generate(Math::random);
46 show("randoms", randoms);
47
48 Stream<BigInteger> integers = Stream.iterate(BigInteger.ONE,
49 n -> n.add(BigInteger.ONE));
50 show("integers", integers);
51
52 Stream<String> wordsAnotherWay = Pattern
53 .compile("\\PL+")
54 .splitAsStream(contents);
55 show("wordsAnotherWay", wordsAnotherWay);
56
57 try (Stream<String> lines = Files
58 .lines(path, StandardCharsets.UTF_8)) {
59 show("lines", lines);
60 }
61 }
62}