如何统计HashMap中各Key对应值内指定单词出现次数并重复输出Key
问题描述
我有一个以Key关联句子记录的HashMap,需要统计每个Key对应句子中单词“car”的出现次数,并将该Key按出现次数重复输出。例如Key5对应句子中“car”出现4次,就输出4次5。当前代码输出为:Car : [1, 2, 3, 5],期望输出为:Car : [1, 1, 2, 3, 3, 5, 5, 5, 5]。
原代码如下:
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()) { if (entrySection.getValue().contains("car")) { showCarsInMap.add(entrySection.getKey()); } } System.out.println("Car : " + showCarsInMap);
我猜测需要添加额外循环,但不知道如何让程序统计“car”的出现次数并按次数添加Key。
解决方案
要实现需求,核心是两步:统计每个句子中"car"的出现次数,根据次数重复添加对应Key到列表。
关键修改点
- 准确统计"car"次数:使用正则匹配独立单词,避免误统计包含"car"的其他词汇(如"carpet")。
- 循环添加Key:根据统计出的次数,循环对应次数将Key加入结果列表。
修改后的代码:
import java.util.HashMap; import java.util.ArrayList; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; public class CarCountDemo { 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"); // 编译正则,匹配独立的"car"单词,忽略大小写 Pattern pattern = Pattern.compile("\\bcar\\b", Pattern.CASE_INSENSITIVE); for (Map.Entry<Integer, String> entrySection : carHashMap.entrySet()) { String sentence = entrySection.getValue(); Matcher matcher = pattern.matcher(sentence); int count = 0; // 统计匹配到的次数 while (matcher.find()) { count++; } // 按次数重复添加Key for (int i = 0; i < count; i++) { showCarsInMap.add(entrySection.getKey()); } } System.out.println("Car : " + showCarsInMap); } }
代码说明
\\bcar\\b中的\\b是单词边界,确保只匹配独立的"car"单词;Pattern.CASE_INSENSITIVE可以兼容"Car"、"CAR"等大小写形式,不需要的话可移除该参数。- 通过
while(matcher.find())逐个统计匹配项,比split()方法更准确,不会因为分隔符问题漏统计或多统计。 - 内层循环根据统计的次数,重复将对应Key添加到列表,最终输出符合预期的结果。
内容的提问来源于stack exchange,提问作者OnlyProblems
相关产品推荐
相关产品推荐

