Skip to content

Commit c8830dd

Browse files
committed
added word count example to Collectors
1 parent 19385dd commit c8830dd

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

04-collectors.md

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -327,3 +327,20 @@ public class MultisetCollectorExample {
327327
}
328328
}
329329
```
330+
331+
## Word Count in Java 8
332+
333+
We will end this section by writing famous word count example in Java 8 using Streams and Collectors.
334+
335+
```java
336+
public static void wordCount(Path path) throws IOException {
337+
Map<String, Long> wordCount = Files.lines(path)
338+
.parallel()
339+
.flatMap(line -> Arrays.stream(line.trim().split("\\s")))
340+
.map(word -> word.replaceAll("[^a-zA-Z]", "").toLowerCase().trim())
341+
.filter(word -> word.length() > 0)
342+
.map(word -> new SimpleEntry<>(word, 1))
343+
.collect(groupingBy(SimpleEntry::getKey, counting()));
344+
wordCount.forEach((k, v) -> System.out.println(String.format("%s ==>> %d", k, v)));
345+
}
346+
```

0 commit comments

Comments
 (0)