我正在尝试对 HasMap ArrayList 进行排序,以便我的 ListView 按值排序,但我没有得到它。
基本上我有几个键,其中之一是“type”,它保存像 "1", "4", "3",....
这样的值。
我想按此键“类型”对列表进行排序,但我得到 "1", "11", "2"
而不是"1", "2", "11"
...
我正在尝试使用此代码对其进行排序:
Collections.sort(myList, new Comparator<HashMap<String, String>>() {
public int compare(HashMap<String,
String> mapping1,HashMap<String, String> mapping2) {
return mapping1.get("type").compareTo(mapping2.get("type"));
}
});
最佳答案
您的类型是String
,这就是为什么您会得到"1", "11", "2"
。将该字符串转换为整数 (Integer.valueOf()),然后进行比较。
更改以下内容
mapping1.get("type").compareTo(mapping2.get("type"));
到
Integer.valueOf(mapping1.get("type")).compareTo(Integer.valueOf(mapping2.get("type")));
注意:上面的代码我没有编译。
关于java - 使用整数作为字符串对 HashMap<String, String> 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16009250/