java中的map排序
下面通过这个例子简单例子看看map是如何排序的。代码如下:
public static Map<String, Date> map = new HashMap<String, Date>();
public static void getFile(File f) {
File files[] = f.listFiles();
for (int i = 0; files != null && i < files.length; i++) {
if (files[i].isDirectory()) {
getFile(files[i]);
} else {
map.put(files[i].getName(), new Date(files[i].lastModified()));
}
}
}
public static void main(String[] args) {
File f = new File("C:\\Users\\Administrator\\Desktop");
getFile(f);
List<Map.Entry<String, Date>> mappingList = new ArrayList<Map.Entry<String, Date>>(map.entrySet());
Collections.sort(mappingList, new Comparator<Map.Entry<String, Date>>() {
public int compare(Entry<String, Date> o1, Entry<String, Date> o2) {
return o2.getValue().compareTo(o1.getValue());
}
});
for (Map.Entry<String, Date> mapping : mappingList) {
System.out.println("文件名:" + mapping.getKey() + ";最后修改时间:"
+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(mapping.getValue()));
}
}
根据文件修改时间排序