Skip to content

Commit d1b0483

Browse files
committed
using Path.of and closing the stream
1 parent ae9765a commit d1b0483

File tree

1 file changed

+8
-7
lines changed

1 file changed

+8
-7
lines changed

app/pages/learn/01_tutorial/03_getting-to-know-the-language/03_refactoring_to_functional_style/05_converting_to_streams.md

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ public class Sample {
3838
final var filePath = "./Sample.java";
3939
final var wordOfInterest = "public";
4040

41-
try (var reader = Files.newBufferedReader(Paths.get(filePath))) {
41+
try (var reader = Files.newBufferedReader(Path.of(filePath))) {
4242
String line = "";
4343
long count = 0;
4444

@@ -73,25 +73,26 @@ An easy way to turn the contents of a file into a stream of data is using the `l
7373

7474
```java
7575
//Sample.java
76-
import java.util.*;
7776
import java.nio.file.*;
7877

7978
public class Sample {
8079
public static void main(String[] args) {
8180
try {
82-
final var filePath = "./Sample.java";
81+
final var filePath = "./Sample.java";
8382
final var wordOfInterest = "public";
8483

85-
long count = Files.lines(Paths.get(filePath))
86-
.filter(line -> line.contains(wordOfInterest))
87-
.count();
84+
try(var stream = Files.lines(Path.of(filePath))) {
85+
long count = stream.filter(line -> line.contains(wordOfInterest))
86+
.count();
8887

89-
System.out.println(String.format("Found %d lines with the word %s", count, wordOfInterest));
88+
System.out.println(String.format("Found %d lines with the word %s", count, wordOfInterest));
89+
}
9090
} catch(Exception ex) {
9191
System.out.println("ERROR: " + ex.getMessage());
9292
}
9393
}
9494
}
95+
9596
```
9697

9798
Not only does the `lines()` method provide a stream of data over the contents of a file, it remove so much of the cruft around reading the lines. Instead of the external iterator where we fetched one line at a time, the stream makes it possible to use the internal iterator where we can focus on what to do for each line of text as it emerges in the stream's pipeline.

0 commit comments

Comments
 (0)