在地图中排序日期字符串 [英] Sort date strings in map
问题描述
我想根据以下日期对地图对象进行排序
Hi I want to sort map objects based on dates below is the map
testMap.put("06/15/2015", 1);
testMap.put("05/15/2015", 2);
testMap.put("01/15/2016", 4);
testMap.put("07/15/2015", 3);
testMap.put("02/15/2016", 5);
我需要如下所示的输出:
I need output like below sequence:
2015年5月15日
2015年6月15日
2015年7月15日
2016年1月15日
2016年2月15日
我需要像2015年的排序月份那样的输出,然后按排序的顺序开始2016个月
I need ouput like sorted months in 2015 and then starting 2016 months in sorted order
我尝试使用树形图但如果日期字符串为 Date 格式,它就可以工作,任何人都可以按上述顺序进行排序
I have tried using treemap but it used to work if dates strings are in Date format, Can any one help in sorting as above sequence
推荐答案
为 TreeMap
创建自定义比较器:
class DateComparator implements Comparator<String>, Serializable {
public int compare(String date1, String date2) {
int date1Int = convertDateToInteger(date1);
int date2Int = convertDateToInteger(date2);
return date1Int - date2Int;
}
// converts date string with format MM/DD/YYYY to integer of value YYYYMMDD
private int convertDateToInteger(String date) {
String[] tokens = date.split("/");
return Integer.parseInt(tokens[2] + tokens[0] + tokens[1]);
}
}
TreeMap<String, Integer> treeMap = new TreeMap<>(new DateComparator());
这样做的好处是避免了 Date
对象,这可能会降低 put
操作的速度。
This has the benefit of avoiding Date
objects, which may slow put
operations down.
日期字符串,如 2015/06/15
或 2015/05/15
转换为可比较的整数等效项( 20150615
和<$分别按照c $ c> 20150515 的时间顺序排列。
Date strings like 06/15/2015
or 05/15/2015
are converted to comparable integer equivalents (20150615
and 20150515
respectively) in keeping with their chronological order.
然后您可以照常添加键/值对,键将根据比较器进行排序:
You can then add key/value pairs as usual, the keys will be ordered as per the comparator:
treeMap.put("06/15/2015", 1);
treeMap.put("05/15/2015", 2);
treeMap.put("01/15/2016", 4);
treeMap.put("07/15/2015", 3);
treeMap.put("02/15/2016", 5);
这篇关于在地图中排序日期字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!