按日期排序HashMap [英] Sorting a HashMap by date

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

问题描述

在一个Java类中,我有一个方法按日期重新编写现有的HashMap。 HashMap的类型是< String,Object> ,其中的Object包含一个名为expPayDate的字段,而关键字串是一个连续的数字转换成一个字符串。所以我需要循环遍历sourceMap中的项目并查找具有最新日期的项目,然后按照正确的顺序将其复制到tempMap中。我的问题是确定具有最新日期的项目的最佳方式。

使用TreeMap而不是HashMap。使用TreeMap而不是HashMap。它会在插入时自动排序。

 地图<日期,对象> m =新的TreeMap<日期,对象>(); 

另外,如果你有一个已经存在的HashMap并且想创建一个基于它的TreeMap,构造函数:

  Map<日期,对象> sortedMap = new TreeMap<日期,对象>(m); 

希望它能帮助你。


In a Java class I have a method to reOrder an existing HashMap by date. The HashMap is of a type <String, Object> where the Object contains a field called expPayDate and the key string is a sequential number turned into a string.. So I need to loop through the items in the sourceMap and find the item with the newest date then copy it to a tempMap in the correct order. My issue is what is the best way to determine the item with the newest date.

解决方案

Use a TreeMap instead of HashMap. it will be sorted automatically on insertion.

Map< Date, Object> m = new TreeMap< Date, Object>();

Alternatively, if you have an existing HashMap and want to create a TreeMap based on it, pass it to the constructor:

Map< Date, Object> sortedMap = new TreeMap< Date, Object>(m);

Hope it will help you.

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

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