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