0

我正在尝试对我的 HasMap ArrayList 进行排序,以便我的列表视图按值排序,但我没有得到它。基本上我有几个键,其中一个是“类型”,它包含如下值"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"));
    }
});
4

4 回答 4

5

你的类型是 a String,这就是你得到的原因"1", "11", "2"。将该字符串转换为整数 (Integer.valueOf()),然后进行比较。

更改以下内容

mapping1.get("type").compareTo(mapping2.get("type"));

 Integer.valueOf(mapping1.get("type")).compareTo(Integer.valueOf(mapping2.get("type")));

注意:我没有编译上面的代码。

于 2013-04-15T06:54:50.567 回答
1

“类型”的数据类型似乎是String. 因此排序"1", "11", "2"似乎是正确的。将“类型”的数据类型更改为Integer

或者

compare方法中比较Integer.parseInt“类型”的值

于 2013-04-15T06:51:37.740 回答
0

您需要在比较器中处理非整数值,如果如上所述,您希望混合使用StringInteger键。

Collections.sort(myList, new Comparator<HashMap<String, String>>() {
    public int compare(HashMap<String, String> mapping1,
                       HashMap<String, String> mapping2) {
        String valueOne = mapping1.get("type");
        String valueTwo = mapping2.get("type");
        try {
            return Integer.valueOf(valueOne).compareTo(Integer.valueOf(valueTwo));
        } catch(NumberFormatException e) {
            return valueOne.compareTo(valueTwo);
        }
    }
});

(否则,应更改键值Integer以避免其他开发人员出错。)

于 2013-04-15T17:28:04.837 回答
0

你可以做如下..

根据您的需要更改参数..

Set<Entry<String, Integer>> set = map.entrySet();
        List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>(set);
        Collections.sort( list, new Comparator<Map.Entry<String, Integer>>()
        {
            public int compare( Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2 )
            {
                return (o2.getValue()).compareTo( o1.getValue() );
            }
        } );
        for(Map.Entry<String, Integer> entry:list){
            System.out.println(entry.getKey()+" ==== "+entry.getValue());
        }
于 2016-01-01T19:48:26.883 回答