0

我想通过多个键对 Hashmap 进行排序,目前我使用以下代码

Collections.sort(ilv2, new Comparator<HashMap<String,String>>() {
        public int compare(HashMap<String, String> arg0, HashMap<String, String> arg1) {
            // TODO Auto-generated method stub
            Time d1 = Time.valueOf(arg0.get("stamp"));
            Time d2 =Time.valueOf(arg1.get("stamp"));
            return  d1.compareTo(d2);
        }
    });

Hasmap ilv2 按时间键“stamp”排序,但现在我想按键 res_id (int) 排序,然后按时间排序,如 sql 语句“order by res_id, stamp”有什么建议吗?

编辑:基于给定答案的解决方案

Collections.sort(ilv2, new Comparator<HashMap<String,String>>() {
        public int compare(HashMap<String, String> arg0, HashMap<String, String> arg1) {
            // TODO Auto-generated method stub
            int i = 0;
            int r1 = Integer.valueOf(arg0.get("resid"));
            int r2 = Integer.valueOf(arg1.get("resid"));
            i = r1-r2;
            if(i==0){
                Time d1 = Time.valueOf(arg0.get("stamp"));
                Time d2 =Time.valueOf(arg1.get("stamp"));
                 i = d1.compareTo(d2);
            }
            return  i;
        }
    });
4

1 回答 1

1

从我的代码中,是这样的:

public int compare(ProductItemData pr1, ProductItemData pr2) {
                int i = pr1.crossed.compareTo(pr2.crossed);
                if(i==0) {
                    int j = pr1.addTime.compareTo(pr2.addTime);
                    if(j==0)
                        return ((Long)pr1.id).compareTo(pr2.id);
                    else
                        return j;
                }
                return i;
            }

了解 compareTo 返回的内容。

于 2012-11-20T17:56:46.580 回答