【发布时间】:2014-12-27 08:31:57
【问题描述】:
我正在尝试根据词频(即基于值)对地图进行排序。为此我重写了比较器并传递给TreeMap,但我得到了这个奇怪的输出。
public class WordFrequency {
public static String sentence = "one three two two three three four four four";
public static Map<String, Integer> map;
public static void main(String[] args) {
map = new HashMap<>();
String[] words = sentence.split("\\s");
for (String word : words) {
Integer count = map.get(word);
if (count == null) {
count = 1;
} else {
++count;
}
map.put(word, count);
}
Comparator<String> myComparator = new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
if (map.get(s1) < map.get(s2)) {
return -1;
} else if (map.get(s1) > map.get(s2)) {
return 1;
} else {
return 0;
}
}
};
SortedMap<String, Integer> sortedMap = new TreeMap<String, Integer>(myComparator);
System.out.println("Before sorting: " + map);
sortedMap.putAll(map);
System.out.println("After Sorting based on value:" + sortedMap);
}
}
输出:
Before sorting: {two=2, one=1, three=3, four=3}
After sorting based on value:{one=1, two=2, three=3}
预期输出:
{one=1, two=2, four=3,three=3}
【问题讨论】:
-
这有什么奇怪的?
-
可能 TreeMap 不允许重复
-
@SotiriosDelimanolis 四=3 排序后丢失
-
你的
Comparator是如何工作的,究竟? -
@SagarPudi SotiriosDelimanolis 的 cmets 通常要求您思考并检查您当前的代码以自行获得答案。
标签: java collections map treemap