先将 Map 中的 key 和 value 全部取出来封装成 JavaBea 数组,再将这个数组排序,
排序完成后,重新写回 Map 中,写回时采用 LinkedHashMap 可以保证迭代的顺序。
下面的代码可以参考一下:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class Test {
public static void main(String[] args) {
Map map = new HashMap();
map.put("ee", 3);
map.put("b", 1);
map.put("d", 2);
map.put("eee", 3);
map.put("A", 1);
map.put("K", 2);
map.put("ade", 1);
map.put("c", 2);
map.put("aee", 3);
map.put("a", 1);
map.put("faed", 2);
map.put("bdd", 1);
map.put("qec", 2);
map.put("eade", 3);
map.put("Aadf", 1);
map.put("Kqe", 2);
Map sortMap = new Test().sortMap(map);
for(Map.Entry entry : sortMap.entrySet()) {
System.out.println(entry.getKey() + " --> " + entry.getValue());
}
}
public Map sortMap(Map map) {
class MyMap {
private M key;
private N value;
private M getKey() {
return key;
}
private void setKey(M key) {
this.key = key;
}
private N getValue() {
return value;
}
private void setValue(N value) {
this.value = value;
}
}
List> list = new ArrayList>();
for (Iterator i = map.keySet().iterator(); i.hasNext(); ) {
MyMap my = new MyMap();
String key = i.next();
my.setKey(key);
my.setValue(map.get(key));
list.add(my);
}
Collections.sort(list, new Comparator>() {
public int compare(MyMap o1, MyMap o2) {
if(o1.getValue() == o2.getValue()) {
return o1.getKey().compareTo(o2.getKey());
}else{
return (int)(o1.getValue().doubleValue() - o2.getValue().doubleValue());
}
}
});
Map sortMap = new LinkedHashMap();
for(int i = 0, k = list.size(); i < k; i++) {
MyMap my = list.get(i);
sortMap.put(my.getKey(), my.getValue());
}
return sortMap;
}
}
Map map = new HashMap();
map.put("d", 2);
map.put("c", 1);
map.put("b", 1);
map.put("a", 3);
List> infoIds =
new ArrayList>(map.entrySet());
//排序前
for (int i = 0; i < infoIds.size(); i++) {
String id = infoIds.get(i).toString();
System.out.println(id);
}
//d 2
//c 1
//b 1
//a 3
//排序
Collections.sort(infoIds, new Comparator>() {
public int compare(Map.Entry o1, Map.Entry o2) {
//return (o2.getValue() - o1.getValue());
return (o1.getKey()).toString().compareTo(o2.getKey());
}
});
//排序后
for (int i = 0; i < infoIds.size(); i++) {
String id = infoIds.get(i).toString();
System.out.println(id);
}
//根据key排序
//a 3
//b 1
//c 1
//d 2
//根据value排序
//a 3
//d 2
//b 1
//c 1
参考: http://bbs.csdn.net/topics/230054066
http://www.cnblogs.com/lovebread/archive/2009/11/23/1609121.html