java按照map的value排序 转载http://blog.csdn.net/tsingheng/article/details/7909861
java的TreeMap可以排序,只可惜是按照key来排序的,或者重写其他Map的排序算法也都是按照key来排序的,下面贴出来一个按照value排序的算法:
- public class SortMap {
- public static void main(String[] args) throws Exception {
- // TODO code application logic here
- Map<String, Integer> myMap = new LinkedHashMap();
- myMap.put("1", 1);
- myMap.put("2", 4);
- myMap.put("3", 3);
- myMap.put("4", 9);
- myMap.put("5", 6);
- myMap.put("6", 2);
- printMap(myMap);
- myMap = sortMap(myMap);
- printMap(myMap);
- }
- private static void printMap(Map map){
- System.out.println("===================mapStart==================");
- Iterator it = map.entrySet().iterator();
- while(it.hasNext()){
- Map.Entry entry = (Map.Entry) it.next();
- System.out.println(entry.getKey() + ":" + entry.getValue());
- }
- System.out.println("===================mapEnd==================");
- }
- public static Map sortMap(Map oldMap) {
- ArrayList<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(oldMap.entrySet());
- Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
- @Override
- public int compare(Entry<java.lang.String, Integer> arg0,
- Entry<java.lang.String, Integer> arg1) {
- return arg0.getValue() - arg1.getValue();
- }
- });
- Map newMap = new LinkedHashMap();
- for (int i = 0; i < list.size(); i++) {
- newMap.put(list.get(i).getKey(), list.get(i).getValue());
- }
- return newMap;
- }
- }
posted on 2016-01-14 10:29 1130136248 阅读(100) 评论(0) 编辑 收藏 举报