我使用map接口从文件中读取,然后将值存储为键值对.文件格式如下
A 34
B 25
c 50
Run Code Online (Sandbox Code Playgroud)
我将从该文件中读取数据并将其存储为键值对,然后我将向用户显示该数据.我的要求是以这种格式显示结果
C 50
A 34
B 25
Run Code Online (Sandbox Code Playgroud)
因此,我需要按值的降序对地图进行排序.所以我将能够显示这些作为我的结果..我已经阅读了这个并找到下面的代码
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;
}
Run Code Online (Sandbox Code Playgroud)
我希望这会按升序排列值,我只是想知道这种方法是否正确,或者其他一些有效的方法对我有用吗?
dac*_*cwe 49
由于您可以拥有重复值,因此根本不应使用a Set
.改为a List
并改为排序.你entriesSortedByValues
会看起来像这样:
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;
}
Run Code Online (Sandbox Code Playgroud)
注意:在您的示例输出中,值是降序.如果您希望他们升序,请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));
}
Run Code Online (Sandbox Code Playgroud)
输出:
[D=50, C=50, A=34, B=25]
Run Code Online (Sandbox Code Playgroud)
ami*_*ngh 14
写下你自己的comparator
并传递给它TreeMap
class MyComparator implements Comparator {
Map map;
public MyComparator(Map map) {
this.map = map;
}
public int compare(Object o1, Object o2) {
return ((Integer) map.get(o2)).compareTo((Integer) map.get(o1));
}
}
Run Code Online (Sandbox Code Playgroud)
在测试类中
Map<String, Integer> lMap=new HashMap<String, Integer>();
lMap.put("A", 35);
lMap.put("B", 25);
lMap.put("C", 50);
MyComparator comp=new MyComparator(lMap);
Map<String,Integer> newMap = new TreeMap(comp);
newMap.putAll(lMap);
Run Code Online (Sandbox Code Playgroud)
输出:
C=50
A=35
B=25
Run Code Online (Sandbox Code Playgroud)