Map的特性:
Map內(nèi)涵資料是Key -> Value的架構(gòu)集合體,而Key是屬於Set的架構(gòu)集合體,也就是說Key的值是唯一的,而Value的值可以重複。一般常用的物件是HashMap或TreeMap,如果考慮效能的話,建議使用HashMap,如果希望Key值有順序性,就使用TreeMap吧!所以Map的集合體,資料的擺放方式是沒有順序性的,我們需要借助有順序性的集合體List來幫忙。
範(fàn)例資料如下定義:
Map<String, Integer> map_Data = new HashMap<String, Integer>();
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);
現(xiàn)在將Map集合體轉(zhuǎn)換成List集合體,而List物件使用ArrayList來實(shí)做如下:
//將map_Data由Map型態(tài)轉(zhuǎn)成List型態(tài)的list_Data,以便進(jìn)行排序
List<Map.Entry<String, Integer>> list_Data = new ArrayList<Map.Entry<String, Integer>>(map_Data.entrySet());
透過Collections.sort(List l, Comparator c)方法來做排序的動作,由傳入?yún)?shù)可以了解List l就是要排序的資料結(jié)構(gòu)體,另外還需要一個(gè)Comparator c物件,此物件是用來評估List l中的任兩物件的大小值,實(shí)做如下:
//排序
Collections.sort(list_Data, new Comparator<Map.Entry<String, Integer>>()
{
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2)
{
return (o2.getValue() - o1.getValue());
}
});
上方的Comparator c參數(shù)是使用匿名類別的方式來實(shí)做的。
上一篇介紹的Value資料型態(tài)是Integer,那Double型態(tài)怎麼做呢?
因java.util.Comparator這個(gè)interface(介面)的compare方法,其回傳型態(tài)只有整數(shù)型態(tài),定義如下:
int compare(java.lang.Object o1, java.lang.Object o2)
範(fàn)例資料改成如下:
Map<String, Double> map_Data = new HashMap<String, Double>();
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);