Java Map按照Key和Value排序【转】
Java中Map按照Key和Value排序
package kingtool.sort; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.Map.Entry; /** * * @author King * */ public class MapSortTool { public static void main(String[] args) { Map<String, String> map = new TreeMap<String, String>(); map.put("4", "2"); map.put("1", "1"); map.put("9", "3"); map.put("8", "6"); // Map<String, String> resultMap = sortMapByKey(map); //按Key进行排序 Map<String, String> resultMap = sortMapByValue(map); // 按Value进行排序 for (Map.Entry<String, String> entry : resultMap.entrySet()) { System.out.println(entry.getKey() + " " + entry.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 MapKeyStringComparator()); 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 MapValueStringComparator()); 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; } /** * string key升序 * @author King * */ static class MapKeyStringComparator implements Comparator<String>{ @Override public int compare(String str1, String str2) { return str1.compareTo(str2); } } /** * string value升序 * @author King * */ static class MapValueStringComparator implements Comparator<Map.Entry<String, String>> { @Override public int compare(Entry<String, String> entry1, Entry<String, String> entry2) { return entry1.getValue().compareTo(entry2.getValue()); } } /** * tip: 样例中没用到<br/> * double value降序 * @author King * */ static class MapValueNumberComparator implements Comparator<Map.Entry<String, Double>> { @Override public int compare(Entry<String, Double> entry1, Entry<String, Double> entry2) { return entry1.getValue().compareTo(entry2.getValue()); } } }