有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java排序HashMap<String,String>,整数作为字符串

我正在尝试对HasMap ArrayList进行排序,以便我的listview按值排序,但我没有得到它。 基本上,我有几个键,其中一个是“type”,它保存像"1", "4", "3",....这样的值

我想按这个键“type”对列表进行排序,但是我得到的是"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) 个答案

  1. # 1 楼答案

    你可以做如下事情

    根据需要更改参数

    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());
            }
    
  2. # 2 楼答案

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

    更改以下内容

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

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

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

  3. # 3 楼答案

    如果如上所述,您希望混合使用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,以避免其他开发人员的错误。)

  4. # 4 楼答案

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

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