1.2 创建流

1.2 创建流

你已经知道可以通过实现了 Collection 接口的 stream 方法来将集合转化为 stream。当你想要将数组转化为stream 时,那么应该使用静态方法 Stream.of 。

1
2
Stream<String> words = Stream.of(contents.split("[\\P{L}]+"));
// split returns a String[] array

这个方法有 varargs 参数,所以你可以根据参数的不同来创建不同的流。

1
2
3
4
5
Stream<String> song = Stream.of("gently", "down", "the", "stream");
// 使用 Arrays.stream(array, from, to) 方法来从数组的一部分生成流
//使用 Stream.empty 来构建一个没有元素的流
Stream<String> silence = Stream.empty();
// Generic type <String> is inferred; same as Stream.<String>empty()

Stream 接口通过两个静态方法来创建无穷的流,generate() 方法采用没有参数的函数(从技术角度上来说,是Supplier 接口产生的对象)。当流的值需要时,调用此函数来生成值,你可以用以下的方式来创建拥有常量元素的流。

1
2
Stream<String> echos = Stream.generate(() -> "Echo");
Stream<Double> randoms = Stream.generate(Math::random);

要生成一个无穷的序列,例如 0,1,2,3…那么使用迭代会好一点,它获取一个子值和一个函数,然后重复调用此函数来作用于之前的结果。例如

1
2
Stream<BigInteger> integers
= Stream.iterate(BigInteger.ZERO, n -> n.add(BigInteger.ONE));

第一个在序列中的元素为0,然后第二个元素为 f(seed) /1,接着下一个元素为 f(f(seed)) /2,循环往复。

Java API中的许多方法都会产生流。 例如,Pattern类具有方法 splitAsStream(),该方法通过正则表达式拆分CharSequence。 可以使用以下语句将字符串拆分为单词:

1
2
3
4
5
6
Stream<String> words = Pattern.compile("[\\P{L}]+").splitAsStream(contents);
The static Files.lines method returns a Stream of all lines in a file:
try (Stream<String> lines = Files.lines(path))
{
Process lines
}

以下 1.2 的示例程序展示了创建流的各种方法

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
1	package streams;
2
3 import java.io.IOException;
4 import java.math.BigInteger;
5 import java.nio.charset.StandardCharsets;
6 import java.nio.file.Files;
7 import java.nio.file.Path;
8 import java.nio.file.Paths;
9 import java.util.List;
10 import java.util.regex.Pattern;
11 import java.util.stream.Collectors;
12 import java.util.stream.Stream;
13
14 public class CreatingStreams
15 {
16 public static <T> void show(String title, Stream<T> stream)
17 {
18 final int SIZE = 10;
19 List<T> firstElements = stream
20 .limit(SIZE + 1)
21 .collect(Collectors.toList());
22 System.out.print(title + ": ");
23 if (firstElements.size() <= SIZE)
24 System.out.println(firstElements);
25 else
26 {
27 firstElements.remove(SIZE);
28 String out = firstElements.toString();
29 System.out.println(out.substring(0, out.length() - 1) +
", ...]");
30 }
31 }
32
33 public static void main(String[] args) throws IOException
34 {
35 Path path = Paths.get("../gutenberg/alice30.txt");
36 String contents = new String(Files.readAllBytes(path),
37 StandardCharsets.UTF_8);
38
39 Stream<String> words = Stream.of(contents.split("\\PL+"));
40 show("words", words);
41 Stream<String> song = Stream.of("gently", "down", "the", "stream");
42 show("song", song);
43 Stream<String> silence = Stream.empty();
44 show("silence", silence);
45
46 Stream<String> echos = Stream.generate(() -> "Echo");
47 show("echos", echos);
48
49 Stream<Double> randoms = Stream.generate(Math::random);
50 show("randoms", randoms);
51
52 Stream<BigInteger> integers = Stream.iterate(BigInteger.ONE,
53 n -> n.add(BigInteger.ONE));
54 show("integers", integers);
55
56 Stream<String> wordsAnotherWay =
Pattern.compile("\\PL+").splitAsStream(
57
58
59
60
StandardCharsets.UTF_8))
61 {
contents);
show("wordsAnotherWay", wordsAnotherWay);
try (Stream<String> lines = Files.lines(path,
62 show("lines", lines);
63 }
64 }
65 }
java.util.stream.Stream 8
static <T> Stream<T> of(T... values)
Yields a stream whose elements are the given values.
static <T> Stream<T> empty()
Yields a stream with no elements.
static <T> Stream<T> generate(Supplier<T> s)
Yields an infinite stream whose elements are constructed by repeatedly invoking the function s
static <T> Stream<T> iterate(T seed, UnaryOperator<T> f)
Yields an infinite stream whose elements are seed, f invoked on seed, f invoked on the
preceding element, and so on.
java.util.Arrays 1.2
static <T> Stream<T> stream(T[] array, int startInclusive, int endExclusive) 8
Yields a stream whose elements are the specified range of the array.
java.util.regex.Pattern 1.4
• Stream<String> splitAsStream(CharSequence input) 8
Yields a stream whose elements are the parts of the input that are delimited by this pattern.
java.nio.file.Files 7
static Stream<String> lines(Path path) 8
static Stream<String> lines(Path path, Charset cs) 8
Yields a stream whose elements are the lines of the specified file, with the UTF-8 charset or the given charset.
坚持原创技术分享,您的支持将鼓励我继续创作!