對MAP KEY排序 java
package study.base.map; import java.util.Comparator; import java.util.Map; import java.util.TreeMap; public class SortKeyMap { public static void main(String[] args) { SortKeyMap sortMap=new SortKeyMap(); Map<String, Integer> map = new TreeMap<String, Integer>(); map.put("KFC",123456); map.put("WNBA", 4566); map.put("NBA", 333); map.put("CBA", 44444); Map<String, Integer> resultMap = sortMap.sortMapByValue(map); //按Value進行排序 for (Map.Entry<String, Integer> entry : resultMap.entrySet()) { System.out.println(entry.getKey() + " " + entry.getValue()); } } /** * 使用 Map按value進行排序 * @param map * @return */ public Map<String, Integer> sortMapByValue(Map<String, Integer> map) { if (map == null || map.isEmpty()) { return null; } Map<String, Integer> sortMap = new TreeMap<String, Integer>(new MapComparator()); sortMap.putAll(map); return sortMap; } //比較器類 class MapComparator implements Comparator<String> { public int compare(String me1, String me2) { return me1.compareTo(me2); } } }
package study.base.map; 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.Map.Entry; import java.util.TreeMap; public class SortValueMap { public static void main(String[] args) { SortValueMap sortMap=new SortValueMap(); Map<String, Integer> map = new TreeMap<String, Integer>(); map.put("KFC",123456); map.put("WNBA", 4566); map.put("NBA", 333); map.put("CBA", 44444); Map<String, Integer> resultMap = sortMap.sortMapByValue(map); //按Value進行排序 for (Map.Entry<String, Integer> entry : resultMap.entrySet()) { System.out.println(entry.getKey() + " " + entry.getValue()); } } /** * 使用 Map按value進行排序 * @param map * @return */ public Map<String, Integer> sortMapByValue(Map<String, Integer> map) { if (map == null || map.isEmpty()) { return null; } Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>(); List<Map.Entry<String, Integer>> entryList = new ArrayList<Map.Entry<String, Integer>>(map.entrySet()); Collections.sort(entryList, new MapValueComparator()); Iterator<Map.Entry<String, Integer>> iter = entryList.iterator(); Map.Entry<String, Integer> tmpEntry = null; while (iter.hasNext()) { tmpEntry = iter.next(); sortedMap.put(tmpEntry.getKey(), tmpEntry.getValue()); } return sortedMap; } //比較器類 class MapValueComparator implements Comparator<Map.Entry<String, Integer>> { public int compare(Entry<String, Integer> me1, Entry<String, Integer> me2) { return me1.getValue().compareTo(me2.getValue()); } } }