我有一个单词列表,让我们说
我在文件或字符串中有一个非常大的文本
我需要找出我列表中的每个单词,在这个大字符串中这个单词有多少次出现?
我有点期待结果
以上仅仅是4个元素,但是在我的例子中,可能会有几千个元素,我可以遍历每个元素,并在该字符串中找到no.of计数,但考虑到性能,这是否是一个最佳解决方案?你们能帮我找点线索找出最好的办法吗?
发布于 2016-12-06 17:54:04
考虑到需要匹配包含空格的字符串,我倾向于循环遍历目标字符串列表,在该字符串的文本中执行适当转义的regex搜索,并记录regex匹配的数量。
发布于 2016-12-05 23:15:07
您可以通过将主strings拆分为空白并使用Java8的Stream来计算string的数量,例如:
public static void main(String[] args) throws FileNotFoundException {
String s = "a b c d e f d g e a c v d a w s";
Map<String, Long> wordCount = Arrays.stream(s.split("\\s"))
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println(wordCount);
}发布于 2016-12-05 23:54:18
如果您不想使用流,您可以这样做:
String s = "a b c d e f d g e a c v d a w s";
Map<String, Long> wordCount = new HashMap<>();
String[] words = s.split("\\s");
for (String word : words) {
Long count = wordCount.get(word);
if (count == null) {
count = 0L;
}
count = count + 1L;
wordCount.put(word, count);
}
System.out.println(wordCount);https://stackoverflow.com/questions/40984971
复制相似问题