大家可能经常会遇到需要对map,hashtalbe进行排序的需求,并且会为此头疼。不多说,直接上代码:
package com.ddmap.hadoop.db.util;
import java.util.*;
/**
* Created by IntelliJ IDEA.
* User: 杨果
* Date: 12-1-9
* Time: 上午10:50
* 该类是对Map的value进行排序的工具类
*/
public class SortMapByValue {
/***
* 升序
*/
public static Map.Entry[] ascend(Map h) {
Set set = h.entrySet();
Map.Entry[] entries = (Map.Entry[]) set.toArray(new Map.Entry[set
.size()]);
Arrays.sort(entries, new Comparator() {
public int compare(Object arg0, Object arg1) {
Long key1 = Long.valueOf(((Map.Entry) arg0).getValue().toString());
Long key2 = Long.valueOf(((Map.Entry) arg1).getValue().toString());
return key1.compareTo(key2);
}
});
return entries;
}
public static void main(String[] args){
Map map=new HashMap();
map.put("a",1);
map.put("b",2);
map.put("c",-1);
map.put("d",9999);
Map.Entry[] entries= SortMapByValue.ascend(map);
for(int i=0;i<entries.length;i++){
Map.Entry entrie=entries[i];
System.out.println(entrie.getKey()+"="+entrie.getValue());
}
}
}
输出效果如下:
c=-1
a=1
b=2
d=9999