Java 统计字符串出现次数并倒序排序
Java count string occurrence and sort in reverse order
我在尝试计算字符串出现次数并按降序对它们进行排序时遇到了一些麻烦。以下是样本输入列表:
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,计数器是正确的。但是,它只是不按降序排序。有什么想法吗?
谢谢!
虽然您使用 LinkedHashMap
应该会导致结果保持其顺序,但您实际上从未将 collect
操作的结果分配给 sortedTextSegmentList
。因此,您的 forEach
正在迭代您创建的第一张地图,该地图未按照您想要的方式排序。
我认为您一直在查看 "sortedTextSegmentList",其中出现的顺序与您看到的顺序相同,即 "test, to, today, tomorrow"
试试下面的方法:
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 应该具有您要查找的顺序的数据。
我在尝试计算字符串出现次数并按降序对它们进行排序时遇到了一些麻烦。以下是样本输入列表:
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,计数器是正确的。但是,它只是不按降序排序。有什么想法吗?
谢谢!
虽然您使用 LinkedHashMap
应该会导致结果保持其顺序,但您实际上从未将 collect
操作的结果分配给 sortedTextSegmentList
。因此,您的 forEach
正在迭代您创建的第一张地图,该地图未按照您想要的方式排序。
我认为您一直在查看 "sortedTextSegmentList",其中出现的顺序与您看到的顺序相同,即 "test, to, today, tomorrow"
试试下面的方法:
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 应该具有您要查找的顺序的数据。