java -- 對Map按鍵、按值排序java
1.按鍵排序(sort by key)數據結構
直接上代碼 ↓eclipse
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; }
2.按值排序(sort by value)spa
按值排序就相對麻煩些了,沒有直接可用的數據結構能處理相似需求,須要咱們本身轉換一下。code
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; }
3. 後記orm
若是map存儲的是<String,對象>類型的數據 可讓對象實現java.lang.Comparable<>接口,並按照你本身的排序規則重寫compareTo方法!對象