【问题标题】:SortedSet<Date> (TreeSet<Date>) in descending orderSortedSet<Date> (TreeSet<Date>) 降序排列
【发布时间】:2014-06-23 12:45:51
【问题描述】:

我想按降序对SortedSet&lt;Date&gt; 进行排序。

我已尝试使用 Collection 排序和其他选项,但它们都不起作用。

我用谷歌搜索了很多,但没有得到任何解决方案。我的代码如下:

HashMap<Date, ArrayList<HashMap<String, String>>> tlData = new HashMap<Date, ArrayList<HashMap<String, String>>>();
SortedSet<Date> keys;

public void processData(String result) {

        Calendar cal = Calendar.getInstance();
        try {
            JSONArray arr = new JSONArray(result);
            int len = arr.length();
            ArrayList<HashMap<String, String>> tmpList;
            HashMap<String, String> map;

            tlData = new HashMap<Date, ArrayList<HashMap<String, String>>>();
            for (int i = 0; i < len; ++i) {
                JSONObject obj = arr.getJSONObject(i);
                String dateStr = obj.getString("timestamp");
                Date d = df.parse(dateStr);
                cal.setTime(d);
                cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH),
                        cal.get(Calendar.DATE), 0, 0, 0);
                d = cal.getTime();
                tmpList = tlData.get(d);

                if (tmpList == null)
                    tmpList = new ArrayList<HashMap<String, String>>();

                map = new HashMap<String, String>();

                String val = StringEscapeUtils.unescapeXml(StringEscapeUtils
                        .unescapeHtml(obj.getString("ti")));

                map.put("val", val);
                map.put("id", obj.getString("id"));
                tmpList.add(map);
                tlData.put(d, tmpList);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        keys = new TreeSet<Date>(tlData.keySet()); // I want to sort this set to descending order.
    }

【问题讨论】:

    标签: android sorting collections


    【解决方案1】:

    使用反向比较器和所有元素实例化您的 TreeSet

    private static final Comparator<Date> REV_DATE_COMP = new Comparator<Date>() {
        @Override
        public int compare(Date d1, Date d2) {
            return d2.compareTo(d1);
        }
    }     
    // ...
    keys = new TreeSet<Date>(REV_DATE_COMP); // init with reverse comparator
    keys.addAll(tlData.keySet());
    

    【讨论】:

    • 谢谢..它工作正常
    猜你喜欢
    • 2012-11-25
    • 1970-01-01
    • 2012-10-18
    • 1970-01-01
    • 2013-10-13
    • 1970-01-01
    • 1970-01-01
    • 2014-11-26
    • 1970-01-01
    相关资源
    最近更新 更多