Skip to content

Commit e9969dd

Browse files
committed
14章流创建小节翻译完成
1 parent c31e15c commit e9969dd

1 file changed

Lines changed: 46 additions & 0 deletions

File tree

docs/book/14-Streams.md

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -677,7 +677,53 @@ public class ArrayStreams {
677677
678678
### 正则表达式(Regular Expressions)
679679
680+
Java 的正则表达式已经在[字符串]()这一章节介绍过了。Java 8 在 **java.util.regex.Pattern** 中增加了一个新的方法 `splitAsStream()`,这个方法可以根据你所传入的公式将字符序列转化为流。但是这里有一个限制,输入只能是 **CharSequence**,因此不能将流作为 `splitAsStream()` 的参数。
680681
682+
我们再一次查看将文件处理为单词流的过程。这一次,我们使用流将文件分割为单独的字符串,接着使用正则表达式将字符串转化为单词流。
683+
684+
```java
685+
// streams/FileToWordsRegexp.java
686+
import java.io.*;
687+
import java.nio.file.*;
688+
import java.util.stream.*;
689+
import java.util.regex.Pattern;
690+
public class FileToWordsRegexp {
691+
private String all;
692+
public FileToWordsRegexp(String filePath) throws Exception {
693+
all = Files.lines(Paths.get(filePath))
694+
.skip(1) // First (comment) line
695+
.collect(Collectors.joining(" "));
696+
}
697+
public Stream<String> stream() {
698+
return Pattern
699+
.compile("[ .,?]+").splitAsStream(all);
700+
}
701+
public static void
702+
main(String[] args) throws Exception {
703+
FileToWordsRegexp fw = new FileToWordsRegexp("Cheese.dat");
704+
fw.stream()
705+
.limit(7)
706+
.map(w -> w + " ")
707+
.forEach(System.out::print);
708+
fw.stream()
709+
.skip(7)
710+
.limit(2)
711+
.map(w -> w + " ")
712+
.forEach(System.out::print);
713+
}
714+
}
715+
```
716+
717+
输出为:
718+
719+
```java
720+
Not much of a cheese shop really is it
721+
```
722+
723+
在构造器中我们读取了文件中的所有内容(再一次跳过了第一行注释),并将其转化成为单行字符串。现在,当你调用 `stream()` 方法的时候,可以像往常一样获取一个流,但这次你可以多次调用 `stream()` 方法,在已存储的字符串中创建一个新的流。这里有个限制,整个文件必须存储在内存中;在大多数情况下这并不是什么问题,但是这损失了流中非常重要的好处:
724+
725+
1. 流“不需要存储”。当然它们需要一些内部存储,但是这只是序列的一小部分,和持有整个序列所需要的并不相同。
726+
2. 它们是惰性评估的。幸运的是,我们将在稍晚一些的时候查看如何如解决这个问题。
681727
682728
<!-- Intermediate Operations -->
683729

0 commit comments

Comments
 (0)