实现集合的排序可是实现Comparator<T>或者 Comparable<T>
我用Comparator<T>试验了一下,代码如下:
import java.util.*;
public class TreeMapSorted implements Comparator<Map.Entry<String,Integer>>
{
public static void main(String[] args)
{
// TODO code application logic here
TreeMap<String,Integer> treeMap=new TreeMap<String,Integer>();
treeMap.put("zhangsan",4);
treeMap.put("lisi", 3);
treeMap.put("wangwu",1);
treeMap.put("zhaoliu", 5);
treeMap.put("taylor", 2);
//未排序前
Set<Map.Entry<String,Integer>> set=treeMap.entrySet();
for(Map.Entry<String,Integer> entry:set)
{
System.out.println("key=" + entry.getKey() + ", value=" + entry.getValue());
}
//排序后
TestTreeMapSort(treeMap);
}
@Override
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2)
{
return o1.getValue().intValue() - o2.getValue().intValue();
}
public static void TestTreeMapSort(TreeMap<String,Integer> map)
{
List<Map.Entry<String,Integer>> list = new ArrayList<Map.Entry<String,Integer>>(map.entrySet());
//public static <T> void sort(List<T> list,Comparator<? super T> c)
//文档表明Comparator的类型参数至少等于集合的对象或者是它的超类
Collections.sort(list, new TreeMapSorted());
// Iterator<Map.Entry<String,Integer>> i = list.iterator();
// while (i.hasNext()) {
// Map.Entry<String, Integer> entry = i.next();
// System.out.println("key=" + entry.getKey() + ", value=" + entry.getValue());
// }
for(Map.Entry<String,Integer> entry:list)
{
System.out.println("key=" + entry.getKey() + ", value=" + entry.getValue());
}
}
}不会插图,插不进运行结果
[ 本帖最后由 BlackHorse 于 2011-07-16 20:09 编辑 ] |