Map排序的方式有很多種,這里記錄下自己總結(jié)的兩種比較常用的方式:按鍵排序(sort by key), 按值排序(sort by value)。
按鍵排序(sort by key)
jdk內(nèi)置的java.util包下的TreeMap<K,V>既可滿足此類需求,原理很簡(jiǎn)單,其重載的構(gòu)造器之一

有一個(gè)參數(shù),該參數(shù)接受一個(gè)比較器,比較器定義比較規(guī)則,比較規(guī)則就是作用于TreeMap<K,V>的鍵,據(jù)此可實(shí)現(xiàn)按鍵排序。
- public Map<String, String> sortMapByKey(Map<String, String> oriMap) {
- if (oriMap == null || oriMap.isEmpty()) {
- return null;
- }
- Map<String, String> sortedMap = new TreeMap<String, String>(new Comparator<String>() {
- public int compare(String key1, String key2) {
- int intKey1 = 0, intKey2 = 0;
- try {
- intKey1 = getInt(key1);
- intKey2 = getInt(key2);
- } catch (Exception e) {
- intKey1 = 0;
- intKey2 = 0;
- }
- return intKey1 - intKey2;
- }});
- sortedMap.putAll(oriMap);
- return sortedMap;
- }
-
- private int getInt(String str) {
- int i = 0;
- try {
- Pattern p = Pattern.compile("^\\d+");
- Matcher m = p.matcher(str);
- if (m.find()) {
- i = Integer.valueOf(m.group());
- }
- } catch (NumberFormatException e) {
- e.printStackTrace();
- }
- return i;
- }
按值排序(sort by value)
按值排序就相對(duì)麻煩些了,貌似沒(méi)有直接可用的數(shù)據(jù)結(jié)構(gòu)能處理類似需求,需要我們自己轉(zhuǎn)換一下。
Map本身按值排序是很有意義的,很多場(chǎng)合下都會(huì)遇到類似需求,可以認(rèn)為其值是定義的某種規(guī)則或者權(quán)重。
- public Map<String, String> sortMapByValue(Map<String, String> oriMap) {
- Map<String, String> sortedMap = new LinkedHashMap<String, String>();
- if (oriMap != null && !oriMap.isEmpty()) {
- List<Map.Entry<String, String>> entryList = new ArrayList<Map.Entry<String, String>>(oriMap.entrySet());
- Collections.sort(entryList,
- new Comparator<Map.Entry<String, String>>() {
- public int compare(Entry<String, String> entry1,
- Entry<String, String> entry2) {
- int value1 = 0, value2 = 0;
- try {
- value1 = getInt(entry1.getValue());
- value2 = getInt(entry2.getValue());
- } catch (NumberFormatException e) {
- value1 = 0;
- value2 = 0;
- }
- return value2 - value1;
- }
- });
- Iterator<Map.Entry<String, String>> iter = entryList.iterator();
- Map.Entry<String, String> tmpEntry = null;
- while (iter.hasNext()) {
- tmpEntry = iter.next();
- sortedMap.put(tmpEntry.getKey(), tmpEntry.getValue());
- }
- }
- return sortedMap;
- }
本例中先將待排序oriMap中的所有元素置于一個(gè)列表中,接著使用java.util.Collections的一個(gè)靜態(tài)方法

來(lái)排序列表,同樣是用比較器定義比較規(guī)則。排序后的列表中的元素再依次被裝入Map,需要注意的一點(diǎn)是為了肯定的保證Map中元素與排序后的List中的元素的順序一致,使用了LinkedHashMap數(shù)據(jù)類型,雖然該類型不常見(jiàn),但是在一些特殊場(chǎng)合下還是非常有用的。
|