
本文旨在解决如何统计 HashMap 中每个键对应字符串中特定单词的出现次数的问题。通过使用正则表达式,我们可以精确匹配目标单词,并记录其在每个键对应字符串中出现的次数,最终生成一个包含键的列表,列表中键的重复次数对应于该键对应字符串中目标单词的出现次数。
核心思路是遍历 HashMap 的每个键值对,然后使用正则表达式匹配值(字符串)中目标单词的出现次数。每匹配到一个单词,就将对应的键添加到结果列表中。
以下是详细的实现步骤和代码示例:
创建 HashMap 和结果列表:
首先,我们需要一个 HashMap 来存储键值对(键为整数,值为字符串),以及一个 ArrayList 来存储结果(键的列表)。
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class WordCount {
public static void main(String[] args) {
Map<Integer, String> carHashMap = new HashMap<>();
ArrayList<Integer> showCarsInMap = new ArrayList<>();
carHashMap.put(1, "this car is very fast car");
carHashMap.put(2, "i have a old car");
carHashMap.put(3, "my first car was an mercedes and my second car was an audi");
carHashMap.put(4, "today is a good day");
carHashMap.put(5, "car car car car");
// ... 后续代码
}
}遍历 HashMap:
使用 entrySet() 方法遍历 HashMap 的每个键值对。
for (Map.Entry<Integer, String> entrySection : carHashMap.entrySet()) {
// ... 后续代码
}使用正则表达式匹配单词:
针对每个键值对,使用 Pattern 和 Matcher 类来查找目标单词的出现次数。正则表达式 (?:^|W)car(?:$|W) 确保只匹配完整的单词 "car",而不是 "carpet" 等包含 "car" 的字符串。(?:...) 表示非捕获分组,^ 表示字符串的开头,W 表示非单词字符,$ 表示字符串的结尾。
Pattern p = Pattern.compile("(?:^|\W)car(?:$|\W)");
Matcher m = p.matcher(entrySection.getValue());
while (m.find()) {
showCarsInMap.add(entrySection.getKey());
}添加键到结果列表:
每次匹配到目标单词,就将当前键添加到 showCarsInMap 列表中。
输出结果:
最后,输出 showCarsInMap 列表,它包含了所有出现目标单词的键,并且键的重复次数对应于该键对应字符串中目标单词的出现次数。
System.out.println("Car : " + showCarsInMap);完整代码示例:
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class WordCount {
public static void main(String[] args) {
Map<Integer, String> carHashMap = new HashMap<>();
ArrayList<Integer> showCarsInMap = new ArrayList<>();
carHashMap.put(1, "this car is very fast car");
carHashMap.put(2, "i have a old car");
carHashMap.put(3, "my first car was an mercedes and my second car was an audi");
carHashMap.put(4, "today is a good day");
carHashMap.put(5, "car car car car");
for (Map.Entry<Integer, String> entrySection : carHashMap.entrySet()) {
Pattern p = Pattern.compile("(?:^|\W)car(?:$|\W)"); //This will only capture the exact word, as dicussed in the comments.
Matcher m = p.matcher(entrySection.getValue());
while (m.find()) {
showCarsInMap.add(entrySection.getKey());
}
}
System.out.println("Car : " + showCarsInMap);
}
}注意事项:
总结:
通过使用正则表达式,我们可以方便地统计 HashMap 中每个键对应字符串中特定单词的出现次数。这种方法具有较高的灵活性和准确性,可以应用于各种字符串处理场景。 记住根据实际情况调整正则表达式,以确保能够准确匹配目标单词。
以上就是统计 HashMap 中每个键对应字符串中特定单词的出现次数的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号