『壹』 java里,想對hashmap里的key進行排序
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));
}
}
}