如果Map的一个元素(值)是日期,如何对Map< string,string>进行日期排序?

2o7dmzc5  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(245)

如何在Map的一个元素(值)是日期的情况下按日期排序,我必须按日期排序而不删除重复项

Map< String, String> hMap=new HashMap<String, String>();

将所有元素添加到hmap后,hmap中的值

hMap.put("1","a")
hMap.put("2","b")
hMap.put("3","date");// here I can convert it to date by the help of SimpleDateFormat(yyyyMMdd).
wtlkbnrh

wtlkbnrh1#

在java 8中,可以使用以下方法按值对Map进行排序:

DateFormat format = ...
hMap.entrySet().stream()
    .sorted(Comparator.comparing(e -> format.parse(e.getValue())))
    ...

不过你最好还是把它作为 Map<String,Date> 对输入进行解析,而不是在排序过程中。

相关问题