如何对HashMap键进行排序 [英] How to sort HashMap keys

查看:121
本文介绍了如何对HashMap键进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题

HashMap<String, List<AppPrjMilestone>> dateMilestoneMap
                                 = new HashMap<String, List<AppPrjMilestone>>();

我将动态密钥放在Hashmap对象中,如下所示:

I am putting dynamic key in Hashmap object like this:

dateMilestoneMap.put(""+crateDate,value);

最后我得到的结果如下:

Finally I am getting result like this:

("28/01/2012",value)
("01/01/2012",value)
("26/01/2012",value)

我希望以desc或asc顺序返回键值对。我该怎么做?

I want return key value pairs in desc or asc order. How can I do that?

推荐答案

HashMaps没有按照定义存储键的排序顺序。但是,您可以通过以下方式获取键的数组来完成此操作: Object [] keys = map.keySet()。toArray(); 然后使用数组排序列表: Arrays.sort(keys); 并最终迭代每个键并从HashMap中检索值。

HashMaps do not store the sorted order of keys by definition. You can however accomplish this by acquiring an array of the keys via: Object[] keys = map.keySet().toArray(); Then sorting the list with Arrays: Arrays.sort(keys); and finally iterating through each key and retrieving the value from the HashMap.

for(对象键:键){
System.out.println(map.get(key));
}

此处的排序步骤将使算法在O(n lg n)而不是O(n)中运行可以使用排序数据结构。

The sorting step here will make the algorithm run in O(n lg n) rather than O(n) which would be possible using a sorting data structure.

这将按字典顺序对列表进行排序。由于您的问题看起来像是使用常见的美国日期格式,因此将按日,月和最后年份对列表进行排序。这可能不太正确。您可以使用日期的年,月,日字符串格式,也可以采用更合适的密钥对象。 Joda-Time的DateTime和DateTimeComparator非常有用。在调用 Arrays.sort(键,比较器)时,只需使用DateTime作为键和DateTimeComparator实例;

This will sort the list lexicographically. Since it looks like your question uses the common US date format, this will sort the list by day, then month and finally year. This is not likely correct. You can either use a year, month, day string format of the date, or adopt a more appropriate key object. Joda-Time's DateTime and DateTimeComparator would be quite useful. Simply use DateTime as the key and a DateTimeComparator instance when calling Arrays.sort(keys, comparator);.

这篇关于如何对HashMap键进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆