我想通過使用Collections.sort()對地圖元素(基於值)進行排序。問題是我的程序按降序排列元素,而不是按升序排序。我怎樣才能按升序對它進行排序?以下是我的代碼。請問如何根據java中的升序值對地圖元素進行排序?
package hashTableRR;
import java.util.*;
import java.util.Map.Entry;
public class OrderByValue {
public static void main(String [] args){
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put(1, 4);
map.put(2, 6);
map.put(3, 1);
map.put(4, 1);
map.put(6, 8);
map.put(7, 5);
Set<Entry<Integer, Integer>> set = map.entrySet();
List<Entry<Integer, Integer>> list = new ArrayList<Entry<Integer, Integer>>(set);
Collections.sort(list, new Comparator<Map.Entry<Integer, Integer>>()
{
public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2){
return(o2.getValue()).compareTo(o1.getValue());
}
}
);
System.out.println("Keys\t\tValues");
for(Map.Entry<Integer, Integer> entry:list)
{
System.out.println(" "+entry.getKey()+"\t\t "+entry.getValue());
}
}
}
嘗試使用'return(o1.getValue())。compareTo(o2.getValue());'。請注意,比較順序很重要。 – aUserHimself
非常感謝你,它的工作! – Miji05
可能的重複[按值排序圖](http://stackoverflow.com/questions/109383/sort-a-mapkey-value-by-values-java) –