bha*_*ya 5 java sorting hashmap
我有一个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);
Run Code Online (Sandbox Code Playgroud)
当我尝试使用以下键对hashMap进行排序时:Map modified_a = new TreeMap(a); 并按如下方式显示按键:
01-06-2011,10-06-2011,25-05-2011, 31-05-2011
Run Code Online (Sandbox Code Playgroud)
但我希望按键排序为
31-05-2011,25-05-2011,01-06-2011 ,10-06-2011
Run Code Online (Sandbox Code Playgroud)
我可以看到值是根据前2位数(这是日期值)进行排序的,但是我还要考虑月份值,并根据月份排序,然后按月对每个月进行排序.任何线索?
IMO的最佳解决方案是为密钥使用不同的数据类型 - 实际表示日期的数据类型,以及按自然日期顺序排序的数据类型.除非另有限制,否则我会使用Joda Time的LocalDate类型,它代表你想要的东西(只是日期,而不是日期/时间等).
如果你真的想使用字符串键但可以改变它们的格式,你可以使用yyyy-MM-dd格式,这种格式自然是可排序的.
或者,您可以将a传递Comparator<String>给TreeMap构造函数,其中比较器是在要求比较它们时解析两个字符串的比较器,并根据解析的年/月/日值执行比较.虽然没有构造函数同时使用自定义比较器和现有映射,因此您需要以下内容:
Map<String, Integer> modified = new TreeMap<String, Integer>(customComparator);
modified.putAll(a);
Run Code Online (Sandbox Code Playgroud)
如果你有大量数据(由于重复解析),这种方法会相对较慢,并且写得稍微繁琐 - 如果可能的话,我会使用更合适的数据类型.
你可以使用喜欢
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()));
}
Run Code Online (Sandbox Code Playgroud)
我要求对日期进行反向排序(最近的日期首先).我使用下面的代码使它工作:
Map<Date, Integer> dateMap = new TreeMap<Date, Integer>(new Comparator<Date>() {
public int compare(Date date1, Date date2) {
return date2.compareTo(date1);
}
});
Run Code Online (Sandbox Code Playgroud)
调用dateMap.keySet()将导致Set使用键,其中最先返回最近的日期.