java - 在 ArrayList 中搜索单词并将结果保存到地图
问题描述
我在 a 中有一些单词,List<String>
我想在 a 中进行迭代ArrayList<String>
,搜索匹配项并将它们中的每一个(以及它们的出现)放在 a 中Map<String, Integer>
。我写了这个方法:
public Map<String, Integer> findTheWords(ArrayList<String> textInFiles, List<String> words) {
for (int i = 0; i < textInFiles.size(); i++) {
Map<String, Integer> mapResult = new HashMap<>();
for (int j = 0; j < words.size(); j++) {
int count = 0;
Pattern regexp = Pattern.compile("\\b" + words.get(j) + "\\b");
Matcher matcher = regexp.matcher(textInFiles.get(i));
if(matcher.find()) {
while (matcher.find()) {
count++;
}
mapResult.put(textInFiles.get(i), count);
}
}
}
return mapResult;
}
问题在于count
变量并在地图中插入正确的值
解决方案
当你这样做时matcher.find()
,你正在消耗一个事件。
你有两个解决方案:
1)插入时添加一个,这不是很干净和可读
2)插入前测试
int count = 0;
while (matcher.find()) {
count++;
}
if (n>0) mapResult.put(textInFiles.get(i), count);
推荐阅读
- intellij-idea - IntelliJ - 语言级别 5 不支持菱形类型和 Lambda 表达式
- javascript - 如何使用 jquery 访问 $(this) 关键字下的子元素
- javascript - Webpack 热重载非常慢
- asp.net-mvc - 剑道 UI 多重网格
- javascript - Angular Firestore 根据返回的布尔值显示一个按钮,用于检查 Firestore 文档是否存在
- sql - 如何创建连接两个表的视图以显示一个表中的哪些实体未连接到另一个表中的实体?
- symfony - 如何在 Symfony3.4 中通过用户名使用 Lock 组件
- qt - 如何测量 QML 文件中的导入时间?
- amazon-ec2 - 如何调用具有变量的资源名称
- javascript - 无法在表格行上设置焦点