我是TreeMap
和TreeSet
以及喜欢的新手,并且想知道如何按值对数据结构进行排序?我意识到使用TreeSet你可以自动将它按字母顺序排序,但我希望它通过值来订购?有关如何做到这一点的任何想法?
它目前打印像......
当我想要它打印像......
这是我的方法......
ArrayList<String> fullBagOfWords = new ArrayList<String>();
public Map<String, Integer> frequencyOne;
public void termFrequency() throws FileNotFoundException{
Collections.sort(fullBagOfWords);
Set<String> unique = new TreeSet<String>(fullBagOfWords);
PrintWriter pw = new PrintWriter(new FileOutputStream(frequencyFile));
pw.println("Words in Tweets : Frequency of Words");
for (String key : unique) {
int frequency = Collections.frequency(fullBagOfWords, key);
System.out.println(key + ": " + frequency);
pw.println(key + ": " + frequency);
}
pw.close();
}
感谢所有帮助人员。
按密钥命令TreeMap
,我认为你不能使用相同的实现来按值排序。但是你可以通过稍微不同的方法来完成任务:
public Map<String, Integer> countWords(List<String> words) {
Map<String, Integer> result = new Map<>();
for (String word : words) {
if (result.containsKey(word)) {
// the word is already in the map, increment the count
int count = result.get(word) + 1;
result.put(word, count);
} else {
result.put(word, 1);
}
}
return result;
}
然后,您只需要对生成的地图的元素进行排序。您可以通过以下方式执行此操作:
public List<Map.Entry<String, Integer> sortMap(Map<String, Integer> map) {
List<Map.Entry<String, Integer> elements = new LinkedList<>(map.entrySet());
Collections.sort(elements, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2 ) {
return o1.getValue().compareTo(o2.getValue());
}
});
}
因此,您使用第一种方法来计算单词频率,使用第二种方法对其进行排序。
您可以创建一个ArrayList并将每个条目存储在其中,如下所示:
ArrayList<Map.Entry<String, Integer> list = new new ArrayList(map.entrySet());
然后你可以使用比较器对arrayList进行排序,比较器按值来比较:
Collections.sort(list , new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2 ) {
return o1.getValue().compareTo(o2.getValue());
}
});
然后您可以打印arrayList中的条目
尝试这样的事情:
Set<Map.Entry<Integer, Integer>> sorted =
new TreeSet<Map.Entry<Integer, Integer>>(new Comparator<Map.Entry<Integer, Integer>> {
public int compare(Map.Entry<Integer, Integer> first, Map.Entry<Integer, Integer> second) {
return first.getValue().compareTo(second.getValue());
}
public boolean equals(Map.Entry<Integer, Integer> that) {
return this.equals(that);
}
});
这应该给你你想要的。