对作为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); 

当我尝试使用以下键对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 m = new HashMap(); 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 m1 = new TreeMap(m); DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); for (Map.Entry entry : m1.entrySet()) { System.out.println(df.format(entry.getKey())); } 

IMO的最佳解决方案是为密钥使用不同的数据类型 – 实际表示日期的数据类型,以及按自然日期顺序排序的数据类型。 除非另有限制,否则我会使用Joda Time的LocalDate类型,它代表您想要的(只是日期,而不是日期/时间等)。

如果你真的想使用字符串键但可以改变它们的格式,你可以使用yyyy-MM-dd格式,这种格式自然是可排序的。

或者,您可以Comparator传递给TreeMap构造函数,其中比较器是在要求比较它们时解析两个字符串的比较器,并根据解析的年/月/日值执行比较。 虽然没有构造函数同时使用自定义比较器现有映射,因此您需要以下内容:

 Map modified = new TreeMap(customComparator); modified.putAll(a); 

如果您有大量数据(由于重复解析),并且编写稍微繁琐,这种方法会相对较慢 – 如果可能的话,我会使用更合适的数据类型。

我要求对日期进行反向排序(最近的日期首先)。 我使用下面的代码使它工作:

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

调用dateMap.keySet()将导致带有键的Set ,其中首先返回最近的日期。

您必须将自定义比较器传递给TreeMap构造函数,该构造函数将您的键作为日期而不是字符串进行比较(或使用java.util.Date作为键,在这种情况下,它将在日期实现Comparable时发生。)

创建比较器:

 public class DateComparator implements Comparator { public int compare(Date date1, Date date2) { return date1.compareTo(date2); } } 

并使用TreeMap比较器

 Map comparedDates = new TreeMap(new DateComparator()); // here fill you  map like: comparedDates.put(new Date(System.currentTimeMillis()), 123); 

您地图中的所有日期都将被排序。

您可能希望使用TreeMap而不是HashMap并使用提供排序的自定义Comparator创建Map。

这是一个匿名比较器的草稿(不会将String解析为可比较的日期对象):

 new Comparator() { @Override public int compare(String date1, String date2) { // skipping tests! Assuming, all date are well formatted String[] parts1 = date1.split("-"); String[] parts2 = date2.split("-"); String reordered1 = parts1[2] + parts1[1] + parts1[0]; String reordered2 = parts2[2] + parts2[1] + parts2[0]; return reordered1.compareTo(reordered2); } }