排序地图<关键字,值>基于该值的降序 [英] Sorting the Map<Key,Value> in descending order based on the value
问题描述
我正在使用地图界面从文件,然后将其中的值作为键值对存储。文件格式如下
I am using map interface to read from a file and then store the values in that as a key value pair. The file format is as follows
A 34
B 25
c 50
我将从此文件中读取数据,并将其存储为键值对,然后将其显示给用户。我的要求是以这种格式显示结果
I will read the datas from this file and store that as a key value pair and then I will display this to the user. My requirement is to display the results in this format
C 50
A 34
B 25
因此,我需要按照值降序对图进行排序。所以我可以显示这些作为我的结果..我已经阅读了这个,并找到以下代码
Thus I need to sort the map in descending order of the value. So that I will be able to display these as my result .. I have read about this and find the below code
static <K,V extends Comparable<? super V>> SortedSet<Map.Entry<K,V>> entriesSortedByValues(Map<K,V> map) {
SortedSet<Map.Entry<K,V>> sortedEntries = new TreeSet<Map.Entry<K,V>>(
new Comparator<Map.Entry<K,V>>() {
@Override public int compare(Map.Entry<K,V> e1, Map.Entry<K,V> e2) {
int res = e1.getValue().compareTo(e2.getValue());
return res != 0 ? res : 1; // Special fix to preserve items with equal values
}
}
);
sortedEntries.addAll(map.entrySet());
return sortedEntries;
}
我希望这会按升序排列值,我只想知道这种方法是正确的还是其他有效的方法对我有帮助?
I hope this is gonna sort the values in ascending order, I just want to know whether this approach is correct or some other effective approach will be helpful for me ?
推荐答案
由于你可以有重复的值,你应该不要使用 Set
。更改为列表
并对其进行排序。您的 entriesSortedByValues
将如下所示:
Since you can have duplicate values you shouldn't be using a Set
at all. Change to a List
and sort it instead. Your entriesSortedByValues
would look something like this:
static <K,V extends Comparable<? super V>>
List<Entry<K, V>> entriesSortedByValues(Map<K,V> map) {
List<Entry<K,V>> sortedEntries = new ArrayList<Entry<K,V>>(map.entrySet());
Collections.sort(sortedEntries,
new Comparator<Entry<K,V>>() {
@Override
public int compare(Entry<K,V> e1, Entry<K,V> e2) {
return e2.getValue().compareTo(e1.getValue());
}
}
);
return sortedEntries;
}
注意:在你的例子中输出的值是降序。如果你想要他们升序,请使用 e1.getValue()。compareTo(e2.getValue())
。
public static void main(String args[]) {
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("A", 34);
map.put("B", 25);
map.put("C", 50);
map.put("D", 50); // "duplicate" value
System.out.println(entriesSortedByValues(map));
}
输出:
[D=50, C=50, A=34, B=25]
这篇关于排序地图<关键字,值>基于该值的降序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!