LinkedHashMap本身不能排序,它是按照插入的顺序来取数据的,所以这里要把一个正确排序的新的LinkedHashMap对象赋值给原来需要排序的对象:
Map<Long,String> rateStdList=new LinkedHashMap<Long,String>();
//..省略往rateStdList中添加元素的过程
List<Map.Entry<Long, String>> infoIds = new ArrayList<Map.Entry<Long, String>>(rateStdList.entrySet());
// 按照库名中含有养护的费率库放在前面
Collections.sort(infoIds, new Comparator<Map.Entry<Long, String>>() {
public int compare(Map.Entry<Long, String> o1,
Map.Entry<Long, String> o2) {
return (o2.getValue().indexOf("养护")-o1.getValue().indexOf("养护"));
}
});
Map<Long,String> sortRateStdList=new LinkedHashMap<Long,String>();
for (int i = 0; i < infoIds.size(); i++) {
Entry<Long,String> ent=infoIds.get(i);
sortRateStdList.put(ent.getKey(),ent.getValue()) ;
};
//最后把排序号的新的LinkedHashMap赋值给原来的rateStdList
rateStdList = sortRateStdList;
另外再给个实例:
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("lisi", 5);
map.put("lisi1", 1);
map.put("lisi2", 3);
map.put("lisi3", 9);
List<Map.Entry<String, Integer>> infoIds = new ArrayList<Map.Entry<String, Integer>>(
map.entrySet());
System.out.println("--------------排序前--------------");
for (int i = 0; i < infoIds.size(); i++) {
String id = infoIds.get(i).toString();
System.out.println(id);
}
// 排序
Collections.sort(infoIds, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> o1,
Map.Entry<String, Integer> o2) {
return ( o1.getValue()-o2.getValue());
}
});
System.out.println("--------------排序后--------------");
for (int i = 0; i < infoIds.size(); i++) {
Entry<String,Integer> ent=infoIds.get(i);
System.out.println(ent.getKey()+"="+ent.getValue());
}