假设我有一个arraylist如下:
String[] s = {"John","Mary","Jane"};
double[] d = {18,21,34};
ArrayList<HashMap<String, CharSequence>> list1 = new ArrayList<HashMap<String, CharSequence>>();
for(int i = 0; i < 3; i++){
HashMap<String, CharSequence> temp = new HashMap<String, CharSequence>();
temp.put("col1", s[i]);
temp.put("col2", Double.toString(d[i]));
list1.add(temp);
}
如果我想对列表中的任何列进行排序,该怎么做?谢谢。
信息添加:
我试着写一个比较器,但它只能排序第一列。我不知道如何对第二列进行排序。
Collections.sort(list1, new Comparator<HashMap<String, CharSequence>>() {
@Override
public int compare(HashMap<String, CharSequence> s1, HashMap<String, CharSequence> s2)
{
return s1.toString().compareTo(s2.toString());
}
});
添加信息:
我试图修改return语句,但它获得了Nullpointer异常:
return s1.get(1).toString().compareTo(s2.get(1).toString());
添加信息:
谢谢大家。似乎HashMap没有索引器并导致NullPointer异常,现在使用列名解决了问题:
return s1.get("col2").toString().compareTo(s2.get("col2").toString());
答案 0 :(得分:0)
尝试这样的事情,根据你的字符串s
Comparator<String> comparator = new Comparator<String>() {
@Override
public int compare(String key1, String key2) {
int returned = sequence.indexOf(key1) - sequence.indexOf(key2);
//.indexOf(key1) returns the index of the first character of the String
if(returned < 0){
// then it is sorted;
returned 1;
}
else{
returned = -1;}
return returned;
}
};
Map<String,Double> lhm = new TreeMap<String,Double>(comparator);
这不是解决问题的方法,但你可以这样做。