首页 > 代码库 > 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()); } } }
Java Map按照Key和Value排序【转】
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。