Add MostFrequentWordsImpl
This commit is contained in:
@@ -8,7 +8,7 @@ import java.util.Map;
|
||||
public class MainTest {
|
||||
|
||||
public static void main(String[] args) {
|
||||
MostFrequentWords mostFrequentWords = null;
|
||||
MostFrequentWords mostFrequentWords = new MostFrequentWordsImpl();
|
||||
|
||||
Map<String, Integer> result = mostFrequentWords.getNWords("На дворе трава, на траве дрова. Не руби дрова на траве двора!", 3);
|
||||
log.info("3 most frequent words: {}", result);
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
package ru.ilug.c9_most_frequent_words;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class MostFrequentWordsImpl implements MostFrequentWords {
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public Map<String, Integer> getNWords(String text, int count) {
|
||||
return Arrays.stream(text.replaceAll("[.,!]", "").split(" "))
|
||||
.collect(
|
||||
Collectors.groupingBy(c -> c,
|
||||
Collectors.collectingAndThen(Collectors.toList(), List::size)
|
||||
)
|
||||
).entrySet().stream()
|
||||
.sorted(Comparator.comparingInt(e -> ((Map.Entry<String, Integer>)e).getValue()).reversed())
|
||||
.limit(count)
|
||||
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user