本问题已经有最佳答案,请猛点这里访问。
Possible Duplicate:
How to sort a Mapon the values in Java?
我使用map接口读取文件,然后将其中的值作为键值对存储。文件格式如下
A 34
B 25
c 50
我将从这个文件中读取数据并将其存储为键值对,然后将其显示给用户。我的要求是以这种格式显示结果
C 50
A 34
B 25
因此,我需要按值的降序对映射进行排序。这样我就可以把这些作为我的结果显示出来。我已经阅读了相关内容并找到了以下代码
static > SortedSet> entriesSortedByValues(Map map) {
SortedSet> sortedEntries = new TreeSet>(
new Comparator>() {
@Override public int compare(Map.Entry e1, Map.Entry 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;
}
我希望这将按升序对值进行排序,我只想知道这种方法是正确的还是其他有效的方法对我有帮助?
也许你应该看看番石榴。请参阅此评论。
@Nandakumar:Set不允许重复,例如使用List。如果你开始允许的话,你就违反了Comparator的合同!
` map.entryset().stream().排序(comparator.comparising(e->-e.ge‌&8203;tValue()).foreach(s‌&8203;system.out::println);‌&8203;。`
因为可以有重复的值,所以根本不应该使用Set。改为List,然后进行排序。你的entriesSortedByValues看起来像这样:
static >
List> entriesSortedByValues(Map map) {
List> sortedEntries = new ArrayList>(map.entrySet());
Collections.sort(sortedEntries,
new Comparator>() {
@Override
public int compare(Entry e1, Entry e2) {
return e2.getValue().compareTo(e1.getValue());
}
}
);
return sortedEntries;
}
注意:在您的示例中,输出值是降序的。如果你想让它们上升,用e1.getValue().compareTo(e2.getValue())代替。例子:
public static void main(String args[]) {
Map map = new HashMap();
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]
为我工作。谢谢!
每个人都应该使用sortedEntries.sort(),而不是Collections:sortedEntries.sort((e1, e2) -> e2.getValue().compareTo(e1.getValue()));。
写下你自己的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));
}
}
在测试课上
Map lMap=new HashMap();
lMap.put("A", 35);
lMap.put("B", 25);
lMap.put("C", 50);
MyComparator comp=new MyComparator(lMap);
Map newMap = new TreeMap(comp);
newMap.putAll(lMap);
输出:
C=50
A=35
B=25
如果添加lMap.put("D", 50),这不起作用,因为它将被视为一个副本(事实上,它会覆盖50的任何其他值,例如"C")。
不允许重复值。
@谢谢你的友好解决方案。但是,我希望允许重复的值。有什么可能达到同样的效果呢?谢谢您。
以下代码将起作用。public map sortByValue(map map)list=new linkedList(map.entryset());collections.sort(list,new comparator()public int compare(object o2,object o1)return((comparable)((map.entry)(o1)).getValue()).compareTo((map.entry)(o2)).getValue());map result=new linkedhashmap();for(iterator it=list.iterator();it.hasNext();)map.entry entry=(map.entry)it.next();result.put(entry.getkey(),entry.getValue());返回结果;
您应该使用new treemap(collections.reverseOrder());。mapnew map=new treemap(collections.reverseOrder());new map.putall(mymap);