gpt4 book ai didi

java - 排序键是 HashMap 中的日期条目

转载 作者:搜寻专家 更新时间:2023-10-31 08:07:31 25 4
gpt4 key购买 nike

我有一个 hashMap,它具有以下值作为键 value(sql date , integer) 对:

a.put("31-05-2011",67);
a.put("01-06-2011",89);
a.put("10-06-2011",56);
a.put("25-05-2011",34);

当我尝试使用以下键对 hashMap 进行排序时:map modified_a=new TreeMap(a); 并显示如下键:

01-06-2011,10-06-2011,25-05-2011, 31-05-2011

但我希望键被排序为

31-05-2011,25-05-2011,01-06-2011 ,10-06-2011

我可以看到值是根据前 2 位数字(这是日期值)排序的,但我还需要考虑月份值并首先根据月份排序,然后对每个月对相应的日期进行排序.有什么线索吗??

最佳答案

你可以像这样使用

Map<Date, Integer> m = new HashMap<Date, Integer>(); 

DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");

m.put(new java.sql.Date(dateFormat.parse("31-05-2011").getTime()),67);
m.put(new java.sql.Date(dateFormat.parse("01-06-2011").getTime()),89);
m.put(new java.sql.Date(dateFormat.parse("10-06-2011").getTime()),56);
m.put(new java.sql.Date(dateFormat.parse("25-05-2011").getTime()),34);


Map<Date, Integer> m1 = new TreeMap(m);
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");

for (Map.Entry<Date, Integer> entry : m1.entrySet())
{
System.out.println(df.format(entry.getKey()));
}

关于java - 排序键是 HashMap 中的日期条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6261237/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com