針對java.util.Map的Value做排序1
来源:百度文库 编辑:神马文学网 时间:2024/04/18 19:34:56
Map的特性:
Map內涵資料是Key -> Value的架構集合體,而Key是屬於Set的架構集合體,也就是說Key的值是唯一的,而Value的值可以重複。一般常用的物件是HashMap或TreeMap,如果考慮效能的話,建議使用HashMap,如果希望Key值有順序性,就使用TreeMap吧!所以Map的集合體,資料的擺放方式是沒有順序性的,我們需要借助有順序性的集合體List來幫忙。
範例資料如下定義:
Map
map_Data.put("A", 98);
map_Data.put("B", 50);
map_Data.put("C", 76);
map_Data.put("D", 23);
map_Data.put("E", 85);
System.out.println(map_Data);
現在將Map集合體轉換成List集合體,而List物件使用ArrayList來實做如下:
//將map_Data由Map型態轉成List型態的list_Data,以便進行排序
List
透過Collections.sort(List l, Comparator c)方法來做排序的動作,由傳入參數可以了解List l就是要排序的資料結構體,另外還需要一個Comparator c物件,此物件是用來評估List l中的任兩物件的大小值,實做如下:
//排序
Collections.sort(list_Data, new Comparator
{
public int compare(Map.Entry
{
return (o2.getValue() - o1.getValue());
}
});
System.out.println(list_Data);
http://140.123.26.152/portfolio/NUBlog/article.php?u=695430005&i=20080412
針對java.util.Map的Value做排序(2)
上一篇介紹的Value資料型態是Integer,那Double型態怎麼做呢?
因java.util.Comparator這個interface(介面)的compare方法,其回傳型態只有整數型態,定義如下:
int compare(java.lang.Object o1, java.lang.Object o2)
範例資料改成如下:
Map
map_Data.put("A", 98.89);
map_Data.put("B", 50.777);
map_Data.put("C", 76.566);
map_Data.put("D", 23.001);
map_Data.put("E", 23.899);
//排序
Collections.sort(list_Data, new Comparator
{
public int compare(Map.Entry
{
return (o2.getValue() - o1.getValue());
}
});
return (int)(o2.getValue() - o1.getValue());
這樣做會發生一個問題,注意資料中("D", 23.001)、("E", 23.899),這兩筆資料在強制轉型後,都是23,沒有辦法準確反映出浮點數的部份,解決方法不難,先確定要取得的小數點位數是多少,像此範例剛好都是小數點三位,那就取到小數點三位,再強制轉成整數,這樣就可以排出正確大小了。程式碼修改如下:
return (int)((o2.getValue() - o1.getValue()) * 1000.0); (#)