SortedSet <date>(TreeSet <date>)按降序排列</date> </date>

时间:2014-06-23 12:45:51

标签: android sorting collections

我想按降序排序SortedSet<Date>

我尝试了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.
    }

1 个答案:

答案 0 :(得分:0)

使用反向比较器和所有元素({/ p>)实现您的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());