这是工具类中的代码
package com.demo.utils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class SortUtils {
/**
* 给map集合中的key实现字典排序
* @param map
* @return
*/
public Map<String , Object> MapKeySort(Map<String , Object> map){
ArrayList list = new ArrayList();
for (Map.Entry<String, Object> entry : map.entrySet()) {
list.add(entry.getKey());
//System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
}
HashMap<String , Object> newMap = new HashMap<String , Object>();
//运用Collections的sort()方法对其进行排序 sort()方法需要传 连个参数,一个是需要进行排序的Collection 另一个是一个Comparator
Collections.sort(list, new SpellComparatorUtils());
for (int i = 0; i < list.size(); i++) {
newMap.put(list.get(i).toString() , map.get(list.get(i).toString()));
}
return newMap;
}
}
这是比较类
package com.demo.utils;
import java.util.Comparator;
public class SpellComparatorUtils implements Comparator {
public int compare(Object o1, Object o2) {
try {
// 取得比较对象的汉字编码,并将其转换成字符串
String s1 = new String(o1.toString().getBytes("GB2312"), "ISO-8859-1");
String s2 = new String(o2.toString().getBytes("GB2312"), "ISO-8859-1");
// 运用String类的 compareTo()方法对两对象进行比较
return s1.compareTo(s2);
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
}
请自行更改package !!!