Map排序的方式有很多種,這里記錄下自己總結的兩種比較常用的方式:按鍵排序(sort by key), 按值排序(sort by value)。
按鍵排序(sort by key)
jdk內置的java.util包下的TreeMap<K,V>既可滿足此類需求,原理很簡單,其重載的構造器之一
有一個參數,該參數接受一個比較器,比較器定義比較規(guī)則,比較規(guī)則就是作用于TreeMap<K,V>的鍵,據此可實現按鍵排序。
- 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)
按值排序就相對麻煩些了,貌似沒有直接可用的數據結構能處理類似需求,需要我們自己轉換一下。
Map本身按值排序是很有意義的,很多場合下都會遇到類似需求,可以認為其值是定義的某種規(guī)則或者權重。
- 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中的所有元素置于一個列表中,接著使用java.util.Collections的一個靜態(tài)方法
來排序列表,同樣是用比較器定義比較規(guī)則。排序后的列表中的元素再依次被裝入Map,需要注意的一點是為了肯定的保證Map中元素與排序后的List中的元素的順序一致,使用了LinkedHashMap數據類型,雖然該類型不常見,但是在一些特殊場合下還是非常有用的。
本站僅提供存儲服務,所有內容均由用戶發(fā)布,如發(fā)現有害或侵權內容,請
點擊舉報。