我們都知道,java中的Map結構是key->value鍵值對存儲的,而且根據Map的特性,同一個Map中 不存在兩個Key相同的元素,而value不存在這個限制。換句話說,在同一個Map中Key是唯一的,而value不唯一。Map是一個接口,我們不能 直接聲明一個Map類型的對象,在實際開發中,比較常用的Map性數據結構是HashMap和TreeMap,它們都是Map的直接子類。如果考慮到存取 效率的話,建議使用HashMap數據結構,而如果需要考慮到Key的順序,建議使用TreeMap,但是TreeMap在刪除、添加過程中需要排序,性能比較差。
- 以Key進行排序
我們可以聲明一個TreeMap對象Map<Integer, Person> map =
new
TreeMap<Integer, Person>();
然后往map中添加元素,可以通過輸出結果,可以發現map里面的元素都是排好序的
//遍歷集合
for
(Iterator<Integer> it = map.keySet().iterator(); it.hasNext();) {
Person person = map.get(it.next());
System.out.println(person.getId_card() +
" "
+ person.getName());
}
我們也可以聲明一個HashMap對象,然后把HashMap對象賦值給TreeMap,如下:
Map<Integer, Person> map =
new
HashMap<Integer, Person>();
TreeMap treemap =
new
TreeMap(map);
- 以Value進行排序
先聲明一個HashMap對象:Map<String, Integer> map =
new
HashMap<String, Integer>();
然后我們可以將Map集合轉換成List集合中,而List使用ArrayList來實現如下:
List<Entry<String,Integer>> list =
new
ArrayList<Entry<String,Integer>>(map.entrySet());
最后通過Collections.sort(List l, Comparator c)方法來進行排序,代碼如下:
Collections.sort(list,
new
Comparator<Map.Entry<String, Integer>>() {
public
int
compare(Map.Entry<String, Integer> o1,
Map.Entry<String, Integer> o2) {
return
(o2.getValue() - o1.getValue());
}
});
上述代碼是講map中的value按照逆序排序,如果需要按照升序進行排序的話,只需要修改o2.getValue() - o1.getValue()為o1.getValue() - o2.getValue()即可