【问题标题】:How to sort map with a date key in reverse order?如何以相反的顺序使用日期键对地图进行排序?
【发布时间】:2014-11-01 15:32:21
【问题描述】:

我有一个哈希映射,其中日期作为键存储,数组列表是一个值。 我想对地图进行排序,以便首先显示最新日期,最后显示旧日期。

例如,我们有 4 个日期作为键,例如“01-09-2014”、“02-09-2014”、“31-08-2014”、“30-08-2014”;

所以输出应该是“02-09-2014”、“01-09-2014”、“31-08-2014”、“30-08-2014”

请帮我解决这个问题。

谢谢。

【问题讨论】:

标签: java


【解决方案1】:
static void sortMap() throws Exception{
    DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");

    Map<Date, Integer> map = new TreeMap<Date, Integer>(new Comparator<Date>() {
        public int compare(Date date1, Date date2) {
            return date2.compareTo(date1);
        }
    });

    map.put(dateFormat.parse("01-09-2014"), 1);
    map.put(dateFormat.parse("02-09-2014"), 2);
    map.put(dateFormat.parse("31-08-2014"), 3);
    map.put(dateFormat.parse("30-08-2014"), 4);
}

【讨论】:

    【解决方案2】:

    试试这个

    public static void main(String[] args) {
            Map<Date, Integer> m = new HashMap<Date, Integer>();
    
            DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
    
            try {
                m.put(dateFormat.parse("31-05-2011").getTime(), 67);
                m.put(dateFormat.parse("01-06-2011").getTime(), 89);
                m.put(dateFormat.parse("10-06-2011").getTime(), 56);
                m.put(dateFormat.parse("25-05-2011").getTime(), 34);
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    
            Map<Date, Integer> m1 = new TreeMap(m, new Comparator<Date>() {
              @Override
              public int compareTo(Date a, Date b) {
                return -a.compare(b);
              }
            });
            DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
    
            for (Map.Entry<Date, Integer> entry : m1.entrySet()) {
                System.out.println(df.format(entry.getKey()));
            }
        }
    

    【讨论】:

    • 这就是他在 m1 中使用 TreeMap 的原因。但它应该覆盖比较器(按自然顺序排列日期,而不是倒序)。
    • @NoDataFound 这个new TreeMap(m),有Date 作为键,同样Date 类覆盖compareTo 方法。
    • @assylias 这个新的TreeMap(m),以Date 作为键,同时Date 类覆盖compareTo 方法
    • @NoDataFound 只是为了清除您的 cmets,请参考this
    • @NoDataFound 我现在可以投票而不是反对
    【解决方案3】:

    使用TreeMap 并定义一个适当的Comparator 那个相反的东西(例如:(Date a, Date b) -&gt; -a.compare(b));

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多