项目开发过程中,总会遇到各种没有遇见过的需求,今天遇到了一个map排序问题。
Map<String,Object> testMap = new HashMap<String,Object>();
KEY 值的规则是这样的:
xxxxx/xxxxxx/xxxxx/201304;
xxxxx/xxxxxx/xxxxx/201305;
xxxxx/xxxxxx/xxxxx/201304a;
xxxxx/xxxxxx/xxxxx/201304b;
xxxxx/xxxxxx/xxxxx/201305b;
xxxxx/xxxxxx/xxxxx/201305a;
要求按照如下顺序输出 value:
xxxxx/xxxxxx/xxxxx/201304;
xxxxx/xxxxxx/xxxxx/201304a;
xxxxx/xxxxxx/xxxxx/201305;
xxxxx/xxxxxx/xxxxx/201305a;
xxxxx/xxxxxx/xxxxx/201305b;
xxxxx/xxxxxx/xxxxx/201404b;
即按照最后一个斜杠后面的字符串按照 ascll 码排序的顺序输出 value,解决方法如下:
public class Test {
public static void main(String[] args) {
//模拟 Object[] keys = test.keySet().toArray();
Object[] keys ={"dsfecsae/200915","bhfsef/200912a","bdewst/200912","vfwdeasfa/200912","bgsefeea/200913a","jgsdrfa/200914"};
//创建比较器
Comparator<Object> comparator = new Comparator<Object>() {
//重写比较器方法
@Override
public int compare(Object o1, Object o2) {
String str1 = (String)o1;
String str2 = (String)o2;
//截取KEY值最后一个斜杠后面的字符串
String temp1 = str1.substring(str1.lastIndexOf("/")+1, str1.length());
String temp2 = str2.substring(str2.lastIndexOf("/")+1, str2.length());
//组成字符数组
String[] temps = {temp1,temp2};
//ASCLL排序
Arrays.sort(temps);
//如果字符数组第一个字符串和temp1相等,则返回 -1
if(temps[0].equals(temp1)){
return -1;
}
//如果 temp1 和temp2 相等
if (temp1.equals(temp2))
return 0;
else
return 1;
}
};
//对keys 排序
Arrays.sort(keys, comparator);
System.out.println("==================");
for(String test:strs){
System.out.println(": "+test);
}
System.out.println("==================");
for(String key:keys){
Object obj = testMap.get(key);
........
.......
....
..
}
}
}
运行结果:
==================
vfwdeasfa/200912
bdewst/200912
bgsefeea/200913a
jgsdrfa/200914
dsfecsae/200915
bhfsef/201012a
==================
小生乃菜鸟一枚,如若写的有差池或各位有更好的方法,还望各位提出,大家共同进步。