/**
* 对Map的值排序
*/
public Map<Object, Integer> sortMapByValue() {
Map<Object, Integer> ret = new LinkedHashMap<Object, Integer>();
List<Map.Entry<Integer, Integer>> infoIds = new ArrayList<Map.Entry<Integer, Integer>>(BROKER_CREDIT_RESULT.entrySet());
// 排序
Collections.sort(infoIds, new Comparator<Map.Entry<Integer, Integer>>() {
public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {
if (o2.getValue() == o1.getValue()) {
return BROKER_CREDIT[o2.getKey()] - BROKER_CREDIT[o1.getKey()]
}
return (o2.getValue() - o1.getValue());
}
});
// 排序后
for (int i = 0; i < infoIds.size(); i++) {
ret.put infoIds.get(i).getKey(), infoIds.get(i).getValue()
}
return ret
}
* 对Map的值排序
*/
public Map<Object, Integer> sortMapByValue() {
Map<Object, Integer> ret = new LinkedHashMap<Object, Integer>();
List<Map.Entry<Integer, Integer>> infoIds = new ArrayList<Map.Entry<Integer, Integer>>(BROKER_CREDIT_RESULT.entrySet());
// 排序
Collections.sort(infoIds, new Comparator<Map.Entry<Integer, Integer>>() {
public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {
if (o2.getValue() == o1.getValue()) {
return BROKER_CREDIT[o2.getKey()] - BROKER_CREDIT[o1.getKey()]
}
return (o2.getValue() - o1.getValue());
}
});
// 排序后
for (int i = 0; i < infoIds.size(); i++) {
ret.put infoIds.get(i).getKey(), infoIds.get(i).getValue()
}
return ret
}
*******************************************************
- import java.util.Comparator;
- public class KeyComparator implements Comparator<Object> {
- public int compare(Object arg0, Object arg1) {
- int muti0 = (Integer) arg0;
- int muti1 = (Integer) arg1;
- if (muti0 < muti1) {
- return 1;
- } else {
- return 0;
- }
- }
- }
然后写一个测试类,实现HashMap按value排序。
- public class Test{
- public static void main(String[] args){
- KeyComparator com = new KeyComparator();
- Map<String,Integer> map = new HashMap<String,Integer>();
- map.put("a",3);
- map.put("b",1);
- map.put("c",2);
- List<Integer> list = new ArrayList<Integer>(map.values());
- Collections.sort(list,com);
- for(Map.Entry<String,Integer> entry:map.entrySet){
- System.out.println(entry.getValue());
- }
- }
- }
输出结果为:3,2,1
如果要实现HashMap按key进行排序,只需要修改如下代码:
int muti0 = (Integer) arg0;
int muti1 = (Integer) arg1;
修改为:
String muti0 = (String) arg0;
String muti1 = (String) arg1;
List<Integer> list = new ArrayList<Integer>(map.values());
修改为:
List<String> list = new ArrayList<String>(map.keySet());
System.out.println(entry.getValue());
修改为:
System.out.println(entry.getKey());
输出结果为:c,b,a