如何按多个值作为日期对HashMap条目进行排序
假设我有一个键为String且值为2个日期的Object的地图。
按对象中的两个日期进行排序
Map<String, dateWrapper> map = new HashMap<>();
map.put("user10",new dateWrapper("20180131","20181231"));
map.put("user3",new dateWrapper("20170131","20171231"));
map.put("user5",new dateWrapper("20160131","20161231"));
map.put("user1",new dateWrapper("20170131","20170131"));
**注意:上面的字符串通过使用SimpleDateFormat解析为日期
预计输出为user5,user1,user3,user10
公共类dateWrapper实现了可序列化的{
private Date date1;
private Date date2;
}
List<Map.Entry<String, dateWrapper>> dateWrapperEntries = new ArrayList<>(map.entrySet());
Trying below this but its returning null
Collections.sort(dateWrapperEntries, Map.Entry.comparingByValue(Comparator.comparing(dateWrapper::getDate1).thenComparing(dateWrapper::getDate2)));
private static Date convertStringToDate(String inputStr) {
Date inputDate = null;
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyyMMdd");
try {
inputDate = sdf.parse(inputStr);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return inputDate;
}
答案 0 :(得分:1)
public static List<String> sort(Map<String, dateWrapper> map) {
// comparator to compare two dateWrapper from Map.Entry value
final Comparator<Map.Entry<String, dateWrapper>> comparator =
Comparator.comparing((Function<Map.Entry<String, dateWrapper>, Date>)e -> e.getValue().getDate1())
.thenComparing(e -> e.getValue().getDate2());
// convert map to entry set and compare it
return Optional.ofNullable(map).orElse(Collections.emptyMap()).entrySet().stream()
.sorted(comparator)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
}