Java计数字符串的出现和排序顺序相反
我在尝试计算字符串出现次数并按降序排序时遇到了一些问题。以下是示例输入列表:Java计数字符串的出现和排序顺序相反,java,string,sorting,linkedhashmap,Java,String,Sorting,Linkedhashmap,我在尝试计算字符串出现次数并按降序排序时遇到了一些问题。以下是示例输入列表: test, test, to, to, to, to, today, tomorrow, today 所需输出的顺序如下: to, test, today tomorrow 下面是我计算字符串出现次数并按相反顺序排序的代码: Map<String, Integer> sortedTextSegmentList = new LinkedHashMap<String, Integer>();
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
));
当我尝试打印时:
sortedTextSegmentList.forEach((key, value) -> {
System.out.println("KEY" + key);
System.out.println("VALUE " + value);
});
明天1,今天2,我要进行测试2到4,计数器是正确的。但是,它只是不按降序排序。有什么想法吗
谢谢 虽然使用LinkedHashMap会使结果保持其顺序,但实际上您从未将收集操作的结果分配给sortedTextSegmentList。因此,您的forEach正在迭代您创建的第一个映射,该映射没有按照您希望的方式进行排序。我想您一直在查看sortedTextSegmentList,它的出现顺序与您看到的顺序相同,即测试、到、今天、明天 请尝试以下内容:
LinkedHashMap sortedMap = 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
));
sortedMap应该按照您要查找的顺序保存数据。您可能希望使用树形图或sortedMap查看:您正在丢弃已排序的地图并打印原始…@shmosel如何访问已排序的地图?sortedTextSegmentList=sortedTextSegmentList.entrySet.stream.sorted…collect。。。;我知道我知道这很有效。谢谢
LinkedHashMap sortedMap = 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
));