按日期键在Java中排序地图 [英] Sorting a map by date key in Java
本文介绍了按日期键在Java中排序地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用TreeMap按日期键在java中排序地图。这是我的代码
I'm trying to sort a map in java by date key using TreeMap. Here's my code
public static void sort() {
BufferedReader br;
String line;
String[] data;
Date date ;
DateFormat df = new SimpleDateFormat("dd-mm-YYY");
Map<Date,String> map = new TreeMap<Date,String>();
try {
br = new BufferedReader(new FileReader(
"/home/user/Desktop/train/2013-training_set.txt"));
int i=0;
while ((line = br.readLine()) != null) {
++i;
data = line.split(":");
map.put(df.parse(data[1]), line);
}
System.out.println(map.size()+" i = "+i);
Set st = mp.entrySet();
Iterator it = st.iterator();
while (it.hasNext()) {
Map.Entry me = (Map.Entry) it.next();
System.out.print(me.getKey() + "->:");
System.out.println(me.getValue());
}
} catch (Exception e) {
e.printStackTrace();
}
}
date [1]
包含字符串格式的日期,如(21-3-2013)。问题是它存储在TreeMap(mp)中只有12个键值对(每个月一个),而不是103(i)预期。任何想法?
The date[1]
contains the date in string format and looks like (e.g. 21-3-2013). The problem is that it stores in the TreeMap(mp) only 12 key-value pairs(one for each month) instead of the 103(i) expected. Any ideas ?
推荐答案
请参阅 http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html 。
年份中使用y,年份中为M,月中为d。具体来说,小写字母m以小时为单位,而大写字母M为年份的月份。
Use y for year, M for month in year, and d for day in month. Specifically, lowercase m is minute in hour, while uppercase M is month in year.
这篇关于按日期键在Java中排序地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文