java里,想对hashmap里的key进行排序
但是用Object[]key=result.keySet().toArray();Arrays.sort(key);排出来不是我想要的结果,因为key里存的是"ch1",...
但是用Object[] key=result.keySet().toArray();
Arrays.sort(key);
排出来不是我想要的结果,因为key里存的是"ch1","ch2","ch13",这样的编号,用这个排序得到的是ch1,ch10,ch11,ch12...ch2,ch20...这种字符串排序,请问怎么解决?
回uestcfb:这样做,岂不是要把map里所有的key全处理一遍,再排序。。。而且还要改变key的类型吗? 展开
Arrays.sort(key);
排出来不是我想要的结果,因为key里存的是"ch1","ch2","ch13",这样的编号,用这个排序得到的是ch1,ch10,ch11,ch12...ch2,ch20...这种字符串排序,请问怎么解决?
回uestcfb:这样做,岂不是要把map里所有的key全处理一遍,再排序。。。而且还要改变key的类型吗? 展开
2个回答
展开全部
chNNN -> NNN -> Integer.parseInt(NNN)
"ch10" -> "10" -> Integer.parseInt("10") -> 10
--------
Yes, you are right, but not too slow/difficult:
import java.util.*;
public class Tmp {
public static void main(String[] args) {
Map<String, Object> result = new HashMap<String, Object>();
result.put("ch1", "ch 1");
result.put("ch111", "ch 111");
result.put("ch11", "ch 11");
result.put("ch2", "ch 2");
result.put("ch13", "ch 13");
Object[] keys=result.keySet().toArray();
Comparator<Object> c = new Comparator<Object>(){
@Override
public int compare(Object o1, Object o2) {
//TODO: add argument check yourself
int a1 = Integer.parseInt(((String)o1).substring(2));
int a2 = Integer.parseInt(((String)o2).substring(2));
if(a1>a2)return 1;
if(a1==a2)return 0;
else return -1;
}
};
Arrays.sort(keys, c);
for(Object s:keys){
System.out.println(s +"=>"+result.get(s));
}
}
}
"ch10" -> "10" -> Integer.parseInt("10") -> 10
--------
Yes, you are right, but not too slow/difficult:
import java.util.*;
public class Tmp {
public static void main(String[] args) {
Map<String, Object> result = new HashMap<String, Object>();
result.put("ch1", "ch 1");
result.put("ch111", "ch 111");
result.put("ch11", "ch 11");
result.put("ch2", "ch 2");
result.put("ch13", "ch 13");
Object[] keys=result.keySet().toArray();
Comparator<Object> c = new Comparator<Object>(){
@Override
public int compare(Object o1, Object o2) {
//TODO: add argument check yourself
int a1 = Integer.parseInt(((String)o1).substring(2));
int a2 = Integer.parseInt(((String)o2).substring(2));
if(a1>a2)return 1;
if(a1==a2)return 0;
else return -1;
}
};
Arrays.sort(keys, c);
for(Object s:keys){
System.out.println(s +"=>"+result.get(s));
}
}
}
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询