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.TreeMap;
public class T {
public static void main(String[] args) {
TreeMap<Character,Integer> tm = new TreeMap<Character,Integer>();
tm.put('a', 1);
tm.put('c', 3);
tm.put('y', 6);
tm.put('f', 2);
System.out.println(sort(tm));
}
/** TreeMap的顺序是自然顺序(如整数从小到大),也可以指定比较函数。但不是插入的顺序
* 返回LinkedHashMap,以支持插入的顺序 */
private static LinkedHashMap<Character,Integer> sort(TreeMap<Character,Integer> map) {
List<Map.Entry<Character,Integer>> list = new ArrayList<Map.Entry<Character,Integer>>();
Iterator<Map.Entry<Character,Integer>> iter = map.entrySet().iterator();
while(iter.hasNext()) {
Map.Entry<Character,Integer> entry = iter.next();
list.add(entry);
}
Collections.sort(list, new Comparator<Object>() {
@SuppressWarnings("unchecked")
@Override
public int compare(Object o1, Object o2) {
Map.Entry<Character,Integer> entry1 = (Map.Entry<Character,Integer>)o1;
Map.Entry<Character,Integer> entry2 = (Map.Entry<Character,Integer>)o2;
return entry1.getValue() - entry2.getValue();
}
});
LinkedHashMap<Character,Integer> sortedMap = new LinkedHashMap<Character,Integer>();
for(Map.Entry<Character,Integer> entry : list) {
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}
}
有不明白的站短我
|