核心比较器
比较器之根据键排序
package cn.com.hongyitech.accountsystem.utils; import java.util.Comparator; class MapKeyComparator implements Comparator<String>{ @Override public int compare(String key1, String key2) { return key1.compareTo(key2); } }
比较器之根据值排序
package cn.com.hongyitech.accountsystem.utils; import java.util.Comparator; import java.util.Map; import java.util.Map.Entry; class MapValueComparator implements Comparator<Map.Entry<String, String>> { @Override public int compare(Entry<String, String> map1, Entry<String, String> map2) { return map1.getValue().compareTo(map2.getValue()); } }
根据键排序
/** * 使用 Map按key进行排序 * * @param map * @return */ public static Map<String, String> sortMapByKey(Map<String, String> map) { if (map == null || map.isEmpty()) { return null; } Map<String, String> sortMap = new TreeMap<String, String>(new MapKeyComparator()); sortMap.putAll(map); return sortMap; }
根据值排序
/** * 使用 Map按value进行排序 * * @param map * @return */ public static Map<String, String> sortMapByValue(Map<String, String> oriMap) { if (oriMap == null || oriMap.isEmpty()) { return null; } Map<String, String> sortedMap = new LinkedHashMap<String, String>(); List<Map.Entry<String, String>> entryList = new ArrayList<Map.Entry<String, String>>(oriMap.entrySet()); Collections.sort(entryList, new MapValueComparator()); 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; }
测试用例
public static void main(String[] args) { Map<String, String> map = new TreeMap<String, String>(); map.put("2018-12-06", "1"); map.put("2018-12-03", "2"); map.put("2018-12-07", "4"); map.put("2018-12-04", "2"); map.put("2018-12-01", "3"); Map<String, String> resultMapByKey = sortMapByKey(map); // 按Key进行排序 Map<String, String> resultMapByValue = sortMapByValue(map); // 按Value进行排序 for (Map.Entry<String, String> entry : resultMapByKey.entrySet()) { System.out.println(entry.getKey() + " " + entry.getValue()); } System.out.println("******上面根据key*********************下面根据value********"); for (Map.Entry<String, String> entry : resultMapByValue.entrySet()) { System.out.println(entry.getKey() + " " + entry.getValue()); } }
结果
2018-12-01 3 2018-12-03 2 2018-12-04 2 2018-12-06 1 2018-12-07 4 ******上面根据key*********************下面根据value******** 2018-12-06 1 2018-12-03 2 2018-12-04 2 2018-12-01 3 2018-12-07 4