简体   繁体   English

排序键是 hashmap 中的日期条目

[英]Sort keys which are date entries in a hashmap

I have a hashMap which has the following values as key value(sql date, integer) pairs:我有一个 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);

when i try to sort the hashMap based on the keys using: Map modified_a=new TreeMap(a);当我尝试根据使用的键对 hashMap 进行排序时: Map modified_a=new TreeMap(a); and display the keys it is as follows:并显示按键如下:

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

but I want the keys to be sorted as但我希望将键排序为

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

I can see that the values are being sorted based on the first 2 digits( which is the date value) but I need the month value to also be considered and sort based on months first and then for each month sort the corresponding days.我可以看到这些值是根据前 2 位数字(即日期值)进行排序的,但我还需要考虑月份值并首先根据月份进行排序,然后每个月对相应的日期进行排序。 Any clues??有什么线索吗??

The best solution IMO would be to use a different data type for the keys - a data type which actually represents a date, and which sorts in natural date order.最好的解决方案 IMO 将使用不同的数据类型作为键 - 一种实际表示日期的数据类型,并按自然日期顺序排序。 Unless otherwise constrained, I'd use Joda Time 's LocalDate type, which represents exactly what you want (just a date, not a date/time etc).除非另有限制,否则我会使用Joda TimeLocalDate类型,它完全代表您想要的(只是一个日期,而不是日期/时间等)。

If you really want to use string keys but can change the format of them, you could use a yyyy-MM-dd format, which is naturally sortable.如果您确实想使用字符串键但可以更改它们的格式,则可以使用 yyyy-MM-dd 格式,它自然是可排序的。

Alternatively, you could pass in a Comparator<String> to the TreeMap constructor, where the comparator is one which parses two strings when it's asked to compare them, and performs the comparison based on the parsed year/month/day values.或者,您可以Comparator<String>传递给TreeMap构造函数,其中比较器是在要求比较两个字符串时解析两个字符串,并根据解析的年/月/日值执行比较的比较器。 There isn't a constructor which takes both a custom comparator and an existing map though, so you'd need something like:没有一个构造函数可以同时使用自定义比较器现有的 map,所以你需要类似的东西:

Map<String, Integer> modified = new TreeMap<String, Integer>(customComparator);
modified.putAll(a);

This approach will be relatively slow if you have a lot of data (due to the repeated parsing), and slightly fiddly to write - I'd use a more appropriate data type if you possibly can.如果您有大量数据(由于重复解析),这种方法将相对较慢,并且编写起来有点繁琐 - 如果可能的话,我会使用更合适的数据类型。

You can use like你可以使用喜欢

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()));
    }

I had a requirement to reverse sort the dates (most recent date first).我需要对日期进行反向排序(首先是最近的日期)。 I made it work by using the code below:我使用下面的代码使它工作:

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

Calling dateMap.keySet() will result in a Set with keys, in which the most recent dates are returned first.调用dateMap.keySet()将产生一个带键的Set ,其中首先返回最近的日期。

You have to pass a custom comparator to the TreeMap constructor, that will compare your keys as dates instead of strings(or use java.util.Date as key, in which case it will happen out of box as date implements Comparable).您必须将自定义比较器传递给 TreeMap 构造函数,它将您的键作为日期而不是字符串进行比较(或使用 java.util.Date 作为键,在这种情况下,它将在日期实现 Comparable 时立即发生)。

Create comparator:创建比较器:

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

And use comparator with TreeMap并将比较器与 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);

All dates in you Map will be sorted.您 Map 中的所有日期都将被排序。

You may want to use a TreeMap instead of a HashMap and create the Map with a custom Comparator that provides the sorting.您可能希望使用TreeMap而不是HashMap并使用提供排序的自定义Comparator器创建 Map。

Here's a draft for an anonymous comparator (that does not parse the String into a comparable date object):这是一个匿名比较器的草稿(它不会将字符串解析为可比较的日期对象):

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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM