我有一个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位数(这是日期值)排序的,但是我还需要考虑月份值,然后根据月份排序,然后按月对每个月进行排序。 。 任何线索??
答案 0 :(得分:9)
最佳解决方案IMO将为密钥使用不同的数据类型 - 实际表示日期的数据类型,并按自然日期顺序排序。除非另有限制,否则我会使用Joda Time的LocalDate
类型,它代表您想要的内容(只是日期,而不是日期/时间等)。
如果你真的想使用字符串键但可以改变它们的格式,你可以使用yyyy-MM-dd格式,这种格式自然可以排序。
或者,您可以将Comparator<String>
传递给TreeMap
构造函数,其中比较器是在要求比较它们时解析两个字符串的比较器,并执行基于解析的年/月/日值的比较。虽然没有一个构造函数同时将自定义比较器和作为现有的映射,所以你需要这样的东西:
Map<String, Integer> modified = new TreeMap<String, Integer>(customComparator);
modified.putAll(a);
如果你有大量数据(由于重复解析),这种方法会相对较慢,并且写得稍微繁琐 - 如果可能,我会使用更合适的数据类型。
答案 1 :(得分:6)
您可以使用
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()));
}
答案 2 :(得分:5)
我要求对日期进行反向排序(最近的日期排在第一位)。我使用下面的代码使它成功:
Map<Date, Integer> dateMap = new TreeMap<Date, Integer>(new Comparator<Date>() {
public int compare(Date date1, Date date2) {
return date2.compareTo(date1);
}
});
调用dateMap.keySet()
会产生Set
个密钥,其中最新的日期会先返回。
答案 3 :(得分:2)
你必须将一个自定义比较器传递给TreeMap构造函数,它将你的键作为日期而不是字符串进行比较(或者使用java.util.Date作为键,在这种情况下,它会在日期实现时发生,因为它实现了Comparable)
答案 4 :(得分:1)
创建比较器:
public class DateComparator implements Comparator<Date> {
public int compare(Date date1, Date date2) {
return date1.compareTo(date2);
}
}
使用比较器和TreeMap
Map<Date, Integer> comparedDates = new TreeMap<Date, Integer>(new DateComparator());
// here fill you <Date, Integer> map like:
comparedDates.put(new Date(System.currentTimeMillis()), 123);
您地图中的所有日期都将被排序。
答案 5 :(得分:0)
您可能希望使用TreeMap
而不是HashMap
,并使用提供排序的自定义Comparator
创建地图。
这是一个匿名比较器的草稿(不会将String解析为可比较的日期对象):
new Comparator<String>() {
@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);
}
}