计算每个关键字中一个单词在HashMap中出现的次数



我有一个HashMap,其中的语句记录与关联的键一起存储。现在,应该在这里创建一个输出,显示这个索引(键(中单词(在我的例子中是单词"car"(的出现量。例如,如果单词";汽车;在索引(键(中发生5、4次,这5次也应该输出4次。

电流输出为:汽车:[1,2,3,5]

我想要的输出是:汽车:[1,1,2,3,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);

我想我必须添加一个额外的if循环,但我不知道我的程序如何识别哪个"if";汽车;已被计算在内,但尚未计算在内。

我建议您只需使用正则表达式:

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());
}
}

Regex来自这里。

虽然不理想,但这会起作用:

carHashMap.entrySet().stream().forEach(x -> {
long count = Arrays.stream(x.getValue().split(" ")).filter(t -> t.equalsIgnoreCase("car")).count();
while (count-- > 0) {
showCarsInMap.add(x.getKey());
}
});

在这里,我认为你只会有空格("(作为分隔符。此外,您不需要使用for循环,但可以直接在hashmap上使用流。

最新更新