我在计算字符串出现次数并按降序排序时遇到了一些问题。以下是示例输入列表:
test, test, to, to, to, to, today, tomorrow, today
所需输出的顺序如下:
to, test, today tomorrow
下面是我的代码,用于计算字符串出现次数并按相反顺序对其排序:
Map<String, Integer> sortedTextSegmentList = new LinkedHashMap<String, Integer>();
for (String s : textSegmentList) {
if (sortedTextSegmentList.get(s) != null) {
sortedTextSegmentList.put(s, sortedTextSegmentList.get(s) + 1);
} else {
sortedTextSegmentList.put(s, 1);
}
}
sortedTextSegmentList.entrySet().stream()
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (x, y)-> {throw new AssertionError();}, LinkedHashMap::new
));
但是,我得到的输出是:
test, to, today, tomorrow
当我试图打印时:
sortedTextSegmentList.forEach((key, value) -> {
System.out.println("KEY" + key);
System.out.println("VALUE " + value);
});
我要参加考试2,到4,明天1,今天2,计数器是正确的。然而,它只是没有按降序排序。有什么想法吗?
谢谢!