Coverage Summary for Class: WordCountService (io.github.mkuchin.service.word)
Class | Class, % | Method, % | Line, % |
---|---|---|---|
WordCountService | 100% (1/ 1) | 100% (6/ 6) | 100% (20/ 20) |
1 package io.github.mkuchin.service.word;
2
3 import io.github.mkuchin.model.WordCountVO;
4
5 import java.util.Arrays;
6 import java.util.LinkedHashMap;
7 import java.util.List;
8 import java.util.Map;
9 import java.util.stream.Collectors;
10 import java.util.stream.Stream;
11
12 import static java.util.function.Function.identity;
13
14 public class WordCountService {
15
16 private final Map<String, Long> wordCount;
17 private final List<WordCountVO> topWords;
18
19 public WordCountService(Stream<String> lines) {
20 wordCount = lines.flatMap(s -> Arrays.stream(s.split("\\W+")))
21 .collect(
22 Collectors.groupingBy(
23 String::toLowerCase,
24 Collectors.counting()
25 )
26 );
27
28 topWords = wordCount.entrySet().stream().
29 sorted(Map.Entry.<String, Long>comparingByValue().reversed()).
30 map(e -> WordCountVO.builder().
31 word(e.getKey()).
32 count(e.getValue()).
33 build()).
34 collect(Collectors.toList());
35 }
36
37 public Map<String, Long> getWordCount(List<String> words) {
38 return words.stream().
39 collect(
40 Collectors.toMap(
41 identity(),
42 w -> wordCount.getOrDefault(w.toLowerCase(), 0L),
43 (u, v) -> v, //ignore duplicate values
44 LinkedHashMap::new //preserve order of keys
45 )
46 );
47 }
48
49 public Stream<WordCountVO> topWords(int n) {
50 return topWords.stream().
51 limit(n);
52 }
53 }