标签:
package com.huawei.test; 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.Set; public class MapSort { public static void printMap(Map<String,Integer> map){ Set<Map.Entry<String, Integer>> set = map.entrySet(); Iterator<Map.Entry<String, Integer>> it = set.iterator(); while(it.hasNext()){ Map.Entry<String, Integer> entry = it.next(); System.out.println(entry.getKey()+" "+entry.getValue()); } } public static void main(String[] args) { Map<String,Integer> map=new LinkedHashMap<String,Integer>(); map.put("Zhukai",14); map.put("LiJunDong",56); map.put("WoZiji",8); printMap(map); System.out.println("********************************"); Map<String,Integer> newmap = sortMap(map); printMap(newmap); } public static Map<String,Integer> sortMap(Map<String,Integer> map){ List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(map.entrySet()); Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() { @Override public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) { // TODO Auto-generated method stub return o2.getValue()-o1.getValue(); } }); Map<String,Integer> resultMap = new LinkedHashMap<String, Integer>(); Iterator<Map.Entry<String, Integer>> it = list.iterator(); while(it.hasNext()){ Map.Entry<String, Integer> entry = it.next(); resultMap.put(entry.getKey(), entry.getValue()); } return resultMap; } }
标签:
原文地址:http://www.cnblogs.com/liusc0424/p/4570401.html